-
1
require 'active_support/lazy_load_hooks'
-
1
require 'active_record/deprecated_finders/version'
-
-
1
ActiveSupport.on_load(:active_record) do
-
1
require 'active_record/deprecated_finders/base'
-
1
require 'active_record/deprecated_finders/relation'
-
1
require 'active_record/deprecated_finders/dynamic_matchers'
-
1
require 'active_record/deprecated_finders/collection_proxy'
-
1
require 'active_record/deprecated_finders/association_builder'
-
end
-
1
require 'active_record/associations/builder/association'
-
1
require 'active_support/core_ext/module/aliasing'
-
1
require 'active_support/deprecation'
-
-
1
module ActiveRecord::Associations::Builder
-
1
class DeprecatedOptionsProc
-
1
attr_reader :options
-
-
1
def initialize(options)
-
options[:includes] = options.delete(:include) if options[:include]
-
options[:where] = options.delete(:conditions) if options[:conditions]
-
options[:extending] = options.delete(:extend) if options[:extend]
-
-
@options = options
-
end
-
-
1
def to_proc
-
options = self.options
-
proc do |owner|
-
if options[:where].respond_to?(:to_proc)
-
context = owner || self
-
where(context.instance_eval(&options[:where]))
-
.merge!(options.except(:where))
-
else
-
merge(options)
-
end
-
end
-
end
-
-
1
def arity
-
1
-
end
-
end
-
-
1
class Association
-
1
DEPRECATED_OPTIONS = [:readonly, :order, :limit, :group, :having,
-
:offset, :select, :uniq, :include, :conditions, :extend]
-
-
1
self.valid_options += [:select, :conditions, :include, :extend, :readonly]
-
-
1
def initialize_with_deprecated_options(model, name, scope, options)
-
if scope.is_a?(Hash)
-
options = scope
-
deprecated_options = options.slice(*DEPRECATED_OPTIONS)
-
-
if deprecated_options.empty?
-
scope = nil
-
else
-
ActiveSupport::Deprecation.warn(
-
"The following options in your #{model.name}.#{macro} :#{name} declaration are deprecated: " \
-
"#{deprecated_options.keys.map(&:inspect).join(',')}. Please use a scope block instead. " \
-
"For example, the following:\n" \
-
"\n" \
-
" has_many :spam_comments, conditions: { spam: true }, class_name: 'Comment'\n" \
-
"\n" \
-
"should be rewritten as the following:\n" \
-
"\n" \
-
" has_many :spam_comments, -> { where spam: true }, class_name: 'Comment'\n"
-
)
-
scope = DeprecatedOptionsProc.new(deprecated_options)
-
options = options.except(*DEPRECATED_OPTIONS)
-
end
-
end
-
-
initialize_without_deprecated_options(model, name, scope, options)
-
end
-
-
1
alias_method_chain :initialize, :deprecated_options
-
end
-
-
1
class CollectionAssociation
-
include Module.new {
-
1
def valid_options
-
super + [:order, :group, :having, :limit, :offset, :uniq]
-
end
-
1
}
-
end
-
end
-
1
require 'active_support/deprecation'
-
-
1
module ActiveRecord
-
1
module DeprecatedFinders
-
1
class ScopeWrapper
-
1
def self.wrap(klass, scope)
-
if scope.is_a?(Hash)
-
ActiveSupport::Deprecation.warn(
-
"Calling #scope or #default_scope with a hash is deprecated. Please use a lambda " \
-
"containing a scope. E.g. scope :red, -> { where(color: 'red') }"
-
)
-
-
new(klass, scope)
-
elsif !scope.is_a?(Relation) && scope.respond_to?(:call)
-
new(klass, scope)
-
else
-
scope
-
end
-
end
-
-
1
def initialize(klass, scope)
-
@klass = klass
-
@scope = scope
-
end
-
-
1
def call(*args)
-
if @scope.respond_to?(:call)
-
result = @scope.call(*args)
-
-
if result.is_a?(Hash)
-
msg = "Returning a hash from a #scope or #default_scope block is deprecated. Please " \
-
"return an actual scope object instead. E.g. scope :red, -> { where(color: 'red') } " \
-
"rather than scope :red, -> { { conditions: { color: 'red' } } }. "
-
-
if @scope.respond_to?(:source_location)
-
msg << "(The scope was defined at #{@scope.source_location.join(':')}.)"
-
end
-
-
ActiveSupport::Deprecation.warn(msg)
-
end
-
else
-
result = @scope
-
end
-
-
if result.is_a?(Hash)
-
@klass.unscoped.apply_finder_options(result, true)
-
else
-
result
-
end
-
end
-
end
-
-
1
def default_scope(scope = {}, &block)
-
if block_given?
-
super ScopeWrapper.new(self, block), &nil
-
else
-
super ScopeWrapper.wrap(self, scope)
-
end
-
end
-
-
1
def scoped(options = nil)
-
ActiveSupport::Deprecation.warn("Model.scoped is deprecated. Please use Model.all instead.")
-
options ? all.apply_finder_options(options, true) : all
-
end
-
-
1
def all(options = nil)
-
options ? super().all(options) : super()
-
end
-
-
1
def scope(name, body = {}, &block)
-
super(name, ScopeWrapper.wrap(self, body), &block)
-
end
-
-
1
def with_scope(scope = {}, action = :merge)
-
ActiveSupport::Deprecation.warn(
-
"ActiveRecord::Base#with_scope and #with_exclusive_scope are deprecated. " \
-
"Please use ActiveRecord::Relation#scoping instead. (You can use #merge " \
-
"to merge multiple scopes together.)"
-
)
-
-
# If another Active Record class has been passed in, get its current scope
-
scope = scope.current_scope if !scope.is_a?(Relation) && scope.respond_to?(:current_scope)
-
-
previous_scope = self.current_scope
-
-
if scope.is_a?(Hash)
-
# Dup first and second level of hash (method and params).
-
scope = scope.dup
-
scope.each do |method, params|
-
scope[method] = params.dup unless params == true
-
end
-
-
scope.assert_valid_keys([ :find, :create ])
-
relation = construct_finder_arel(scope[:find] || {})
-
relation.default_scoped = true unless action == :overwrite
-
-
if previous_scope && previous_scope.create_with_value && scope[:create]
-
scope_for_create = if action == :merge
-
previous_scope.create_with_value.merge(scope[:create])
-
else
-
scope[:create]
-
end
-
-
relation = relation.create_with(scope_for_create)
-
else
-
scope_for_create = scope[:create]
-
scope_for_create ||= previous_scope.create_with_value if previous_scope
-
relation = relation.create_with(scope_for_create) if scope_for_create
-
end
-
-
scope = relation
-
end
-
-
scope = previous_scope.merge(scope) if previous_scope && action == :merge
-
scope.scoping { yield }
-
end
-
-
1
protected
-
-
# Works like with_scope, but discards any nested properties.
-
1
def with_exclusive_scope(method_scoping = {}, &block)
-
if method_scoping.values.any? { |e| e.is_a?(ActiveRecord::Relation) }
-
raise ArgumentError, <<-MSG
-
New finder API can not be used with_exclusive_scope. You can either call unscoped to get an anonymous scope not bound to the default_scope:
-
-
User.unscoped.where(:active => true)
-
-
Or call unscoped with a block:
-
-
User.unscoped do
-
User.where(:active => true).all
-
end
-
-
MSG
-
end
-
with_scope(method_scoping, :overwrite, &block)
-
end
-
-
1
private
-
-
1
def construct_finder_arel(options = {}, scope = nil)
-
relation = options.is_a?(Hash) ? unscoped.apply_finder_options(options, true) : options
-
relation = scope.merge(relation) if scope
-
relation
-
end
-
end
-
-
1
class Base
-
1
extend DeprecatedFinders
-
end
-
end
-
1
module ActiveRecord
-
1
module Associations
-
1
class CollectionProxy
-
1
def method_missing(method, *args, &block)
-
match = DynamicMatchers::Method.match(klass, method)
-
-
if match && match.is_a?(DynamicMatchers::Instantiator)
-
super do |record|
-
proxy_association.add_to_target(record)
-
yield record if block_given?
-
end
-
else
-
super
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/deprecation'
-
-
1
module ActiveRecord
-
1
module DynamicMatchers
-
1
module DeprecatedFinder
-
1
def body
-
<<-CODE
-
result = #{super}
-
result && block_given? ? yield(result) : result
-
CODE
-
end
-
-
1
def result
-
"all.apply_finder_options(options, true).#{super}"
-
end
-
-
1
def signature
-
"#{super}, options = {}"
-
end
-
end
-
-
1
module DeprecationWarning
-
1
def body
-
"#{deprecation_warning}\n#{super}"
-
end
-
-
1
def deprecation_warning
-
%{ActiveSupport::Deprecation.warn("This dynamic method is deprecated. Please use e.g. #{deprecation_alternative} instead.")}
-
end
-
end
-
-
1
module FindByDeprecationWarning
-
1
def body
-
<<-CODE
-
if block_given?
-
ActiveSupport::Deprecation.warn("Calling find_by or find_by! methods with a block is deprecated with no replacement.")
-
end
-
-
unless options.empty?
-
ActiveSupport::Deprecation.warn(
-
"Calling find_by or find_by! methods with options is deprecated. " \
-
"Build a scope instead, e.g. User.where('age > 21').find_by_name('Jon')."
-
)
-
end
-
-
#{super}
-
CODE
-
end
-
end
-
-
1
class FindBy
-
1
include DeprecatedFinder
-
1
include FindByDeprecationWarning
-
end
-
-
1
class FindByBang
-
1
include DeprecatedFinder
-
1
include FindByDeprecationWarning
-
end
-
-
1
class FindAllBy < Method
-
1
Method.matchers << self
-
1
include Finder
-
1
include DeprecatedFinder
-
1
include DeprecationWarning
-
-
1
def self.prefix
-
"find_all_by"
-
end
-
-
1
def finder
-
"where"
-
end
-
-
1
def result
-
"#{super}.to_a"
-
end
-
-
1
def deprecation_alternative
-
"Post.where(...).all"
-
end
-
end
-
-
1
class FindLastBy < Method
-
1
Method.matchers << self
-
1
include Finder
-
1
include DeprecatedFinder
-
1
include DeprecationWarning
-
-
1
def self.prefix
-
"find_last_by"
-
end
-
-
1
def finder
-
"where"
-
end
-
-
1
def result
-
"#{super}.last"
-
end
-
-
1
def deprecation_alternative
-
"Post.where(...).last"
-
end
-
end
-
-
1
class ScopedBy < Method
-
1
Method.matchers << self
-
1
include Finder
-
1
include DeprecationWarning
-
-
1
def self.prefix
-
"scoped_by"
-
end
-
-
1
def body
-
"#{deprecation_warning} \n where(#{attributes_hash})"
-
end
-
-
1
def deprecation_alternative
-
"Post.where(...)"
-
end
-
end
-
-
1
class Instantiator < Method
-
1
include DeprecationWarning
-
-
1
def self.dispatch(klass, attribute_names, instantiator, args, block)
-
if args.length == 1 && args.first.is_a?(Hash)
-
attributes = args.first.stringify_keys
-
conditions = attributes.slice(*attribute_names)
-
rest = [attributes.except(*attribute_names)]
-
else
-
raise ArgumentError, "too few arguments" unless args.length >= attribute_names.length
-
-
conditions = Hash[attribute_names.map.with_index { |n, i| [n, args[i]] }]
-
rest = args.drop(attribute_names.length)
-
end
-
-
klass.where(conditions).first ||
-
klass.create_with(conditions).send(instantiator, *rest, &block)
-
end
-
-
1
def signature
-
"*args, &block"
-
end
-
-
1
def body
-
<<-CODE
-
#{deprecation_warning}
-
#{self.class}.dispatch(self, #{attribute_names.inspect}, #{instantiator.inspect}, args, block)
-
CODE
-
end
-
-
1
def instantiator
-
raise NotImplementedError
-
end
-
-
1
def deprecation_alternative
-
"Post.#{self.class.prefix}#{self.class.suffix}(name: 'foo')"
-
end
-
end
-
-
1
class FindOrInitializeBy < Instantiator
-
1
Method.matchers << self
-
-
1
def self.prefix
-
"find_or_initialize_by"
-
end
-
-
1
def instantiator
-
"new"
-
end
-
end
-
-
1
class FindOrCreateBy < Instantiator
-
1
Method.matchers << self
-
-
1
def self.prefix
-
"find_or_create_by"
-
end
-
-
1
def instantiator
-
"create"
-
end
-
end
-
-
1
class FindOrCreateByBang < Instantiator
-
1
Method.matchers << self
-
-
1
def self.prefix
-
"find_or_create_by"
-
end
-
-
1
def self.suffix
-
"!"
-
end
-
-
1
def instantiator
-
"create!"
-
end
-
end
-
end
-
end
-
1
require 'active_record/relation'
-
1
require 'active_support/core_ext/module/aliasing'
-
-
1
module ActiveRecord
-
1
class Relation
-
1
module DeprecatedMethods
-
1
VALID_FIND_OPTIONS = [ :conditions, :include, :joins, :limit, :offset, :extend,
-
:order, :select, :readonly, :group, :having, :from, :lock ]
-
-
# The silence_deprecation arg is for internal use, where we have already output a
-
# deprecation further up the call stack.
-
1
def apply_finder_options(options, silence_deprecation = false)
-
ActiveSupport::Deprecation.warn("#apply_finder_options is deprecated") unless silence_deprecation
-
-
relation = clone
-
return relation unless options
-
-
options.assert_valid_keys(VALID_FIND_OPTIONS)
-
finders = options.dup
-
finders.delete_if { |key, value| value.nil? && key != :limit }
-
-
((VALID_FIND_OPTIONS - [:conditions, :include, :extend]) & finders.keys).each do |finder|
-
relation = relation.send(finder, finders[finder])
-
end
-
-
relation = relation.where(finders[:conditions]) if options.has_key?(:conditions)
-
relation = relation.includes(finders[:include]) if options.has_key?(:include)
-
relation = relation.extending(finders[:extend]) if options.has_key?(:extend)
-
-
relation
-
end
-
-
1
def update_all_with_deprecated_options(updates, conditions = nil, options = {})
-
scope = self
-
-
if conditions
-
scope = where(conditions)
-
-
ActiveSupport::Deprecation.warn(
-
"Relation#update_all with conditions is deprecated. Please use " \
-
"Item.where(color: 'red').update_all(...) rather than " \
-
"Item.update_all(..., color: 'red')."
-
)
-
end
-
-
if options.present?
-
scope = scope.apply_finder_options(options.slice(:limit, :order), true)
-
-
ActiveSupport::Deprecation.warn(
-
"Relation#update_all with :limit / :order options is deprecated. " \
-
"Please use e.g. Post.limit(1).order(:foo).update_all instead."
-
)
-
end
-
-
scope.update_all_without_deprecated_options(updates)
-
end
-
-
1
def find_in_batches(options = {}, &block)
-
if (finder_options = options.except(:start, :batch_size)).present?
-
ActiveSupport::Deprecation.warn(
-
"Relation#find_in_batches with finder options is deprecated. Please build " \
-
"a scope and then call find_in_batches on it instead."
-
)
-
-
raise "You can't specify an order, it's forced to be #{batch_order}" if options[:order].present?
-
raise "You can't specify a limit, it's forced to be the batch_size" if options[:limit].present?
-
-
apply_finder_options(finder_options, true).
-
find_in_batches(options.slice(:start, :batch_size), &block)
-
else
-
super
-
end
-
end
-
-
1
def calculate(operation, column_name, options = {})
-
if options.except(:distinct).present?
-
ActiveSupport::Deprecation.warn(
-
"Relation#calculate with finder options is deprecated. Please build " \
-
"a scope and then call find_in_batches on it instead."
-
)
-
-
apply_finder_options(options.except(:distinct), true)
-
.calculate(operation, column_name, :distinct => options[:distinct])
-
else
-
super
-
end
-
end
-
-
1
def find(*args)
-
options = args.extract_options!
-
-
if options.present?
-
scope = apply_finder_options(options, true)
-
-
case finder = args.first
-
when :first, :last, :all
-
ActiveSupport::Deprecation.warn(
-
"Calling #find(#{finder.inspect}) is deprecated. Please call " \
-
"##{finder} directly instead. You have also used finder options. " \
-
"These are also deprecated. Please build a scope instead of using " \
-
"finder options."
-
)
-
-
scope.send(finder)
-
else
-
ActiveSupport::Deprecation.warn(
-
"Passing options to #find is deprecated. Please build a scope " \
-
"and then call #find on it."
-
)
-
-
scope.find(*args)
-
end
-
else
-
case finder = args.first
-
when :first, :last, :all
-
ActiveSupport::Deprecation.warn(
-
"Calling #find(#{finder.inspect}) is deprecated. Please call " \
-
"##{finder} directly instead."
-
)
-
-
send(finder)
-
else
-
super
-
end
-
end
-
end
-
-
1
def first(*args)
-
if args.empty?
-
super
-
else
-
if args.first.kind_of?(Integer) || (loaded? && !args.first.kind_of?(Hash))
-
super
-
else
-
ActiveSupport::Deprecation.warn(
-
"Relation#first with finder options is deprecated. Please build " \
-
"a scope and then call #first on it instead."
-
)
-
-
apply_finder_options(args.first, true).first
-
end
-
end
-
end
-
-
1
def last(*args)
-
if args.empty?
-
super
-
else
-
if args.first.kind_of?(Integer) || (loaded? && !args.first.kind_of?(Hash))
-
super
-
else
-
ActiveSupport::Deprecation.warn(
-
"Relation#last with finder options is deprecated. Please build " \
-
"a scope and then call #last on it instead."
-
)
-
-
apply_finder_options(args.first, true).last
-
end
-
end
-
end
-
-
1
def all(*args)
-
ActiveSupport::Deprecation.warn(
-
"Relation#all is deprecated. If you want to eager-load a relation, you can " \
-
"call #load (e.g. `Post.where(published: true).load`). If you want " \
-
"to get an array of records from a relation, you can call #to_a (e.g. " \
-
"`Post.where(published: true).to_a`)."
-
)
-
apply_finder_options(args.first, true).to_a
-
end
-
-
# ActiveRecord::Relation usually compiled delegator methods at runtime as an optimisation.
-
# However, we want to hook into method_missing in CollectionProxy in order to do extra
-
# stuff around find_or_{create|initialize}_by methods. If a compiled method for the delegation
-
# is defined, then we have no way to hook in because method_missing is never invoked.
-
# Therefore, the purpose of this is simply to prevent the super implementation of
-
# method_missing being called in this case, which prevent the compiled delegation from
-
# being created.
-
1
def method_missing(method, *args, &block)
-
match = DynamicMatchers::Method.match(klass, method)
-
-
if match && match.is_a?(DynamicMatchers::Instantiator)
-
scoping { klass.send(method, *args, &block) }
-
else
-
super
-
end
-
end
-
end
-
-
1
include DeprecatedMethods
-
1
alias_method_chain :update_all, :deprecated_options
-
end
-
end
-
1
require 'arel/crud'
-
1
require 'arel/factory_methods'
-
-
1
require 'arel/expressions'
-
1
require 'arel/predications'
-
1
require 'arel/window_predications'
-
1
require 'arel/math'
-
1
require 'arel/alias_predication'
-
1
require 'arel/order_predications'
-
1
require 'arel/table'
-
1
require 'arel/attributes'
-
1
require 'arel/compatibility/wheres'
-
-
#### these are deprecated
-
1
require 'arel/expression'
-
####
-
-
1
require 'arel/visitors'
-
-
1
require 'arel/tree_manager'
-
1
require 'arel/insert_manager'
-
1
require 'arel/select_manager'
-
1
require 'arel/update_manager'
-
1
require 'arel/delete_manager'
-
1
require 'arel/nodes'
-
-
-
#### these are deprecated
-
1
require 'arel/deprecated'
-
1
require 'arel/sql/engine'
-
1
require 'arel/sql_literal'
-
####
-
-
1
module Arel
-
1
VERSION = '3.0.2'
-
-
1
def self.sql raw_sql
-
Arel::Nodes::SqlLiteral.new raw_sql
-
end
-
-
1
def self.star
-
sql '*'
-
end
-
## Convenience Alias
-
1
Node = Arel::Nodes::Node
-
end
-
1
module Arel
-
1
module AliasPredication
-
1
def as other
-
Nodes::As.new self, Nodes::SqlLiteral.new(other)
-
end
-
end
-
end
-
1
require 'arel/attributes/attribute'
-
-
1
module Arel
-
1
module Attributes
-
###
-
# Factory method to wrap a raw database +column+ to an Arel Attribute.
-
1
def self.for column
-
case column.type
-
when :string, :text, :binary then String
-
when :integer then Integer
-
when :float then Float
-
when :decimal then Decimal
-
when :date, :datetime, :timestamp, :time then Time
-
when :boolean then Boolean
-
else
-
Undefined
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Attributes
-
1
class Attribute < Struct.new :relation, :name
-
1
include Arel::Expressions
-
1
include Arel::Predications
-
1
include Arel::AliasPredication
-
1
include Arel::OrderPredications
-
1
include Arel::Math
-
-
###
-
# Create a node for lowering this attribute
-
1
def lower
-
relation.lower self
-
end
-
end
-
-
1
class String < Attribute; end
-
1
class Time < Attribute; end
-
1
class Boolean < Attribute; end
-
1
class Decimal < Attribute; end
-
1
class Float < Attribute; end
-
1
class Integer < Attribute; end
-
1
class Undefined < Attribute; end
-
end
-
-
1
Attribute = Attributes::Attribute
-
end
-
1
module Arel
-
1
module Compatibility # :nodoc:
-
1
class Wheres # :nodoc:
-
1
include Enumerable
-
-
1
module Value # :nodoc:
-
1
attr_accessor :visitor
-
1
def value
-
visitor.accept self
-
end
-
-
1
def name
-
super.to_sym
-
end
-
end
-
-
1
def initialize engine, collection
-
@engine = engine
-
@collection = collection
-
end
-
-
1
def each
-
to_sql = Visitors::ToSql.new @engine
-
-
@collection.each { |c|
-
c.extend(Value)
-
c.visitor = to_sql
-
yield c
-
}
-
end
-
end
-
end
-
end
-
1
module Arel
-
###
-
# FIXME hopefully we can remove this
-
1
module Crud
-
1
def compile_update values
-
um = UpdateManager.new @engine
-
-
if Nodes::SqlLiteral === values
-
relation = @ctx.from
-
else
-
relation = values.first.first.relation
-
end
-
um.table relation
-
um.set values
-
um.take @ast.limit.expr if @ast.limit
-
um.order(*@ast.orders)
-
um.wheres = @ctx.wheres
-
um
-
end
-
-
# FIXME: this method should go away
-
1
def update values
-
if $VERBOSE
-
warn <<-eowarn
-
update (#{caller.first}) is deprecated and will be removed in ARel 4.0.0. Please
-
switch to `compile_update`
-
eowarn
-
end
-
-
um = compile_update values
-
@engine.connection.update um.to_sql, 'AREL'
-
end
-
-
1
def compile_insert values
-
im = create_insert
-
im.insert values
-
im
-
end
-
-
1
def create_insert
-
InsertManager.new @engine
-
end
-
-
# FIXME: this method should go away
-
1
def insert values
-
if $VERBOSE
-
warn <<-eowarn
-
insert (#{caller.first}) is deprecated and will be removed in ARel 4.0.0. Please
-
switch to `compile_insert`
-
eowarn
-
end
-
@engine.connection.insert compile_insert(values).to_sql
-
end
-
-
1
def compile_delete
-
dm = DeleteManager.new @engine
-
dm.wheres = @ctx.wheres
-
dm.from @ctx.froms
-
dm
-
end
-
-
1
def delete
-
if $VERBOSE
-
warn <<-eowarn
-
delete (#{caller.first}) is deprecated and will be removed in ARel 4.0.0. Please
-
switch to `compile_delete`
-
eowarn
-
end
-
@engine.connection.delete compile_delete.to_sql, 'AREL'
-
end
-
end
-
end
-
1
module Arel
-
1
class DeleteManager < Arel::TreeManager
-
1
def initialize engine
-
super
-
@ast = Nodes::DeleteStatement.new
-
@ctx = @ast
-
end
-
-
1
def from relation
-
@ast.relation = relation
-
self
-
end
-
-
1
def wheres= list
-
@ast.wheres = list
-
end
-
end
-
end
-
1
module Arel
-
1
InnerJoin = Nodes::InnerJoin
-
1
OuterJoin = Nodes::OuterJoin
-
end
-
1
module Arel
-
1
module Expression
-
1
include Arel::OrderPredications
-
end
-
end
-
1
module Arel
-
1
module Expressions
-
1
def count distinct = false
-
Nodes::Count.new [self], distinct
-
end
-
-
1
def sum
-
Nodes::Sum.new [self], Nodes::SqlLiteral.new('sum_id')
-
end
-
-
1
def maximum
-
Nodes::Max.new [self], Nodes::SqlLiteral.new('max_id')
-
end
-
-
1
def minimum
-
Nodes::Min.new [self], Nodes::SqlLiteral.new('min_id')
-
end
-
-
1
def average
-
Nodes::Avg.new [self], Nodes::SqlLiteral.new('avg_id')
-
end
-
-
1
def extract field
-
Nodes::Extract.new [self], field
-
end
-
end
-
end
-
1
module Arel
-
###
-
# Methods for creating various nodes
-
1
module FactoryMethods
-
1
def create_true
-
Arel::Nodes::True.new
-
end
-
-
1
def create_false
-
Arel::Nodes::False.new
-
end
-
-
1
def create_table_alias relation, name
-
Nodes::TableAlias.new(relation, name)
-
end
-
-
1
def create_join to, constraint = nil, klass = Nodes::InnerJoin
-
klass.new(to, constraint)
-
end
-
-
1
def create_string_join to
-
create_join to, nil, Nodes::StringJoin
-
end
-
-
1
def create_and clauses
-
Nodes::And.new clauses
-
end
-
-
1
def create_on expr
-
Nodes::On.new expr
-
end
-
-
1
def grouping expr
-
Nodes::Grouping.new expr
-
end
-
-
###
-
# Create a LOWER() function
-
1
def lower column
-
Nodes::NamedFunction.new 'LOWER', [column]
-
end
-
end
-
end
-
1
module Arel
-
1
class InsertManager < Arel::TreeManager
-
1
def initialize engine
-
super
-
@ast = Nodes::InsertStatement.new
-
end
-
-
1
def into table
-
@ast.relation = table
-
self
-
end
-
-
1
def columns; @ast.columns end
-
1
def values= val; @ast.values = val; end
-
-
1
def insert fields
-
return if fields.empty?
-
-
if String === fields
-
@ast.values = SqlLiteral.new(fields)
-
else
-
@ast.relation ||= fields.first.first.relation
-
-
values = []
-
-
fields.each do |column, value|
-
@ast.columns << column
-
values << value
-
end
-
@ast.values = create_values values, @ast.columns
-
end
-
end
-
-
1
def create_values values, columns
-
Nodes::Values.new values, columns
-
end
-
end
-
end
-
1
module Arel
-
1
module Math
-
1
def *(other)
-
Arel::Nodes::Multiplication.new(self, other)
-
end
-
-
1
def +(other)
-
Arel::Nodes::Grouping.new(Arel::Nodes::Addition.new(self, other))
-
end
-
-
1
def -(other)
-
Arel::Nodes::Grouping.new(Arel::Nodes::Subtraction.new(self, other))
-
end
-
-
1
def /(other)
-
Arel::Nodes::Division.new(self, other)
-
end
-
end
-
end
-
# node
-
1
require 'arel/nodes/node'
-
1
require 'arel/nodes/select_statement'
-
1
require 'arel/nodes/select_core'
-
1
require 'arel/nodes/insert_statement'
-
1
require 'arel/nodes/update_statement'
-
-
# terminal
-
-
1
require 'arel/nodes/terminal'
-
1
require 'arel/nodes/true'
-
1
require 'arel/nodes/false'
-
-
# unary
-
1
require 'arel/nodes/unary'
-
1
require 'arel/nodes/grouping'
-
1
require 'arel/nodes/ascending'
-
1
require 'arel/nodes/descending'
-
1
require 'arel/nodes/unqualified_column'
-
1
require 'arel/nodes/with'
-
-
# binary
-
1
require 'arel/nodes/binary'
-
1
require 'arel/nodes/equality'
-
1
require 'arel/nodes/in' # Why is this subclassed from equality?
-
1
require 'arel/nodes/join_source'
-
1
require 'arel/nodes/delete_statement'
-
1
require 'arel/nodes/table_alias'
-
1
require 'arel/nodes/infix_operation'
-
1
require 'arel/nodes/over'
-
-
# nary
-
1
require 'arel/nodes/and'
-
-
# function
-
# FIXME: Function + Alias can be rewritten as a Function and Alias node.
-
# We should make Function a Unary node and deprecate the use of "aliaz"
-
1
require 'arel/nodes/function'
-
1
require 'arel/nodes/count'
-
1
require 'arel/nodes/extract'
-
1
require 'arel/nodes/values'
-
1
require 'arel/nodes/named_function'
-
-
# windows
-
1
require 'arel/nodes/window'
-
-
# joins
-
1
require 'arel/nodes/inner_join'
-
1
require 'arel/nodes/outer_join'
-
1
require 'arel/nodes/string_join'
-
-
1
require 'arel/nodes/sql_literal'
-
1
module Arel
-
1
module Nodes
-
1
class And < Arel::Nodes::Node
-
1
attr_reader :children
-
-
1
def initialize children, right = nil
-
unless Array === children
-
warn "(#{caller.first}) AND nodes should be created with a list"
-
children = [children, right]
-
end
-
@children = children
-
end
-
-
1
def left
-
children.first
-
end
-
-
1
def right
-
children[1]
-
end
-
-
1
def hash
-
children.hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.children == other.children
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Ascending < Ordering
-
-
1
def reverse
-
Descending.new(expr)
-
end
-
-
1
def direction
-
:asc
-
end
-
-
1
def ascending?
-
true
-
end
-
-
1
def descending?
-
false
-
end
-
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Binary < Arel::Nodes::Node
-
1
attr_accessor :left, :right
-
-
1
def initialize left, right
-
@left = left
-
@right = right
-
end
-
-
1
def initialize_copy other
-
super
-
@left = @left.clone if @left
-
@right = @right.clone if @right
-
end
-
-
1
def hash
-
[@left, @right].hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.left == other.left &&
-
self.right == other.right
-
end
-
1
alias :== :eql?
-
end
-
-
%w{
-
As
-
1
Assignment
-
Between
-
DoesNotMatch
-
GreaterThan
-
GreaterThanOrEqual
-
Join
-
LessThan
-
LessThanOrEqual
-
Matches
-
NotEqual
-
NotIn
-
Or
-
Union
-
UnionAll
-
Intersect
-
Except
-
}.each do |name|
-
17
const_set name, Class.new(Binary)
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Count < Arel::Nodes::Function
-
1
def initialize expr, distinct = false, aliaz = nil
-
super(expr, aliaz)
-
@distinct = distinct
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class DeleteStatement < Arel::Nodes::Binary
-
1
alias :relation :left
-
1
alias :relation= :left=
-
1
alias :wheres :right
-
1
alias :wheres= :right=
-
-
1
def initialize relation = nil, wheres = []
-
super
-
end
-
-
1
def initialize_copy other
-
super
-
@right = @right.clone
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Descending < Ordering
-
-
1
def reverse
-
Ascending.new(expr)
-
end
-
-
1
def direction
-
:desc
-
end
-
-
1
def ascending?
-
false
-
end
-
-
1
def descending?
-
true
-
end
-
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Equality < Arel::Nodes::Binary
-
1
def operator; :== end
-
1
alias :operand1 :left
-
1
alias :operand2 :right
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
-
1
class Extract < Arel::Nodes::Unary
-
1
include Arel::Expression
-
1
include Arel::Predications
-
-
1
attr_accessor :field
-
1
attr_accessor :alias
-
-
1
def initialize expr, field, aliaz = nil
-
super(expr)
-
@field = field
-
@alias = aliaz && SqlLiteral.new(aliaz)
-
end
-
-
1
def as aliaz
-
self.alias = SqlLiteral.new(aliaz)
-
self
-
end
-
-
1
def hash
-
super ^ [@field, @alias].hash
-
end
-
-
1
def eql? other
-
super &&
-
self.field == other.field &&
-
self.alias == other.alias
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class False < Arel::Nodes::Node
-
1
def hash
-
self.class.hash
-
end
-
-
1
def eql? other
-
self.class == other.class
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Function < Arel::Nodes::Node
-
1
include Arel::Expression
-
1
include Arel::Predications
-
1
include Arel::WindowPredications
-
1
attr_accessor :expressions, :alias, :distinct
-
-
1
def initialize expr, aliaz = nil
-
@expressions = expr
-
@alias = aliaz && SqlLiteral.new(aliaz)
-
@distinct = false
-
end
-
-
1
def as aliaz
-
self.alias = SqlLiteral.new(aliaz)
-
self
-
end
-
-
1
def hash
-
[@expressions, @alias, @distinct].hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.expressions == other.expressions &&
-
self.alias == other.alias &&
-
self.distinct == other.distinct
-
end
-
end
-
-
%w{
-
Sum
-
1
Exists
-
Max
-
Min
-
Avg
-
}.each do |name|
-
5
const_set(name, Class.new(Function))
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Grouping < Unary
-
1
include Arel::Predications
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class In < Equality
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
-
1
class InfixOperation < Binary
-
1
include Arel::Expressions
-
1
include Arel::Predications
-
1
include Arel::OrderPredications
-
1
include Arel::AliasPredication
-
1
include Arel::Math
-
-
1
attr_reader :operator
-
-
1
def initialize operator, left, right
-
super(left, right)
-
@operator = operator
-
end
-
end
-
-
1
class Multiplication < InfixOperation
-
1
def initialize left, right
-
super(:*, left, right)
-
end
-
end
-
-
1
class Division < InfixOperation
-
1
def initialize left, right
-
super(:/, left, right)
-
end
-
end
-
-
1
class Addition < InfixOperation
-
1
def initialize left, right
-
super(:+, left, right)
-
end
-
end
-
-
1
class Subtraction < InfixOperation
-
1
def initialize left, right
-
super(:-, left, right)
-
end
-
end
-
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class InnerJoin < Arel::Nodes::Join
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class InsertStatement < Arel::Nodes::Node
-
1
attr_accessor :relation, :columns, :values
-
-
1
def initialize
-
@relation = nil
-
@columns = []
-
@values = nil
-
end
-
-
1
def initialize_copy other
-
super
-
@columns = @columns.clone
-
@values = @values.clone if @values
-
end
-
-
1
def hash
-
[@relation, @columns, @values].hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.relation == other.relation &&
-
self.columns == other.columns &&
-
self.values == other.values
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
###
-
# Class that represents a join source
-
#
-
# http://www.sqlite.org/syntaxdiagrams.html#join-source
-
-
1
class JoinSource < Arel::Nodes::Binary
-
1
def initialize single_source, joinop = []
-
super
-
end
-
-
1
def empty?
-
!left && right.empty?
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class NamedFunction < Arel::Nodes::Function
-
1
attr_accessor :name
-
-
1
def initialize name, expr, aliaz = nil
-
super(expr, aliaz)
-
@name = name
-
end
-
-
1
def hash
-
super ^ @name.hash
-
end
-
-
1
def eql? other
-
super && self.name == other.name
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
###
-
# Abstract base class for all AST nodes
-
1
class Node
-
1
include Arel::FactoryMethods
-
1
include Enumerable
-
-
###
-
# Factory method to create a Nodes::Not node that has the recipient of
-
# the caller as a child.
-
1
def not
-
Nodes::Not.new self
-
end
-
-
###
-
# Factory method to create a Nodes::Grouping node that has an Nodes::Or
-
# node as a child.
-
1
def or right
-
Nodes::Grouping.new Nodes::Or.new(self, right)
-
end
-
-
###
-
# Factory method to create an Nodes::And node.
-
1
def and right
-
Nodes::And.new [self, right]
-
end
-
-
# FIXME: this method should go away. I don't like people calling
-
# to_sql on non-head nodes. This forces us to walk the AST until we
-
# can find a node that has a "relation" member.
-
#
-
# Maybe we should just use `Table.engine`? :'(
-
1
def to_sql engine = Table.engine
-
engine.connection.visitor.accept self
-
end
-
-
# Iterate through AST, nodes will be yielded depth-first
-
1
def each &block
-
return enum_for(:each) unless block_given?
-
-
::Arel::Visitors::DepthFirst.new(block).accept self
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class OuterJoin < Arel::Nodes::Join
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
-
1
class Over < Binary
-
1
include Arel::AliasPredication
-
-
1
def initialize(left, right = nil)
-
super(left, right)
-
end
-
-
1
def operator; 'OVER' end
-
end
-
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class SelectCore < Arel::Nodes::Node
-
1
attr_accessor :top, :projections, :wheres, :groups, :windows
-
1
attr_accessor :having, :source, :set_quantifier
-
-
1
def initialize
-
@source = JoinSource.new nil
-
@top = nil
-
-
# http://savage.net.au/SQL/sql-92.bnf.html#set%20quantifier
-
@set_quantifier = nil
-
@projections = []
-
@wheres = []
-
@groups = []
-
@having = nil
-
@windows = []
-
end
-
-
1
def from
-
@source.left
-
end
-
-
1
def from= value
-
@source.left = value
-
end
-
-
1
alias :froms= :from=
-
1
alias :froms :from
-
-
1
def initialize_copy other
-
super
-
@source = @source.clone if @source
-
@projections = @projections.clone
-
@wheres = @wheres.clone
-
@groups = @groups.clone
-
@having = @having.clone if @having
-
@windows = @windows.clone
-
end
-
-
1
def hash
-
[
-
@source, @top, @set_quantifier, @projections,
-
@wheres, @groups, @having, @windows
-
].hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.source == other.source &&
-
self.top == other.top &&
-
self.set_quantifier == other.set_quantifier &&
-
self.projections == other.projections &&
-
self.wheres == other.wheres &&
-
self.groups == other.groups &&
-
self.having == other.having &&
-
self.windows == other.windows
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class SelectStatement < Arel::Nodes::Node
-
1
attr_reader :cores
-
1
attr_accessor :limit, :orders, :lock, :offset, :with
-
-
1
def initialize cores = [SelectCore.new]
-
@cores = cores
-
@orders = []
-
@limit = nil
-
@lock = nil
-
@offset = nil
-
@with = nil
-
end
-
-
1
def initialize_copy other
-
super
-
@cores = @cores.map { |x| x.clone }
-
@orders = @orders.map { |x| x.clone }
-
end
-
-
1
def hash
-
[@cores, @orders, @limit, @lock, @offset, @with].hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.cores == other.cores &&
-
self.orders == other.orders &&
-
self.limit == other.limit &&
-
self.lock == other.lock &&
-
self.offset == other.offset &&
-
self.with == other.with
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class SqlLiteral < String
-
1
include Arel::Expressions
-
1
include Arel::Predications
-
1
include Arel::AliasPredication
-
1
include Arel::OrderPredications
-
end
-
-
1
class BindParam < SqlLiteral
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class StringJoin < Arel::Nodes::Join
-
1
def initialize left, right = nil
-
super
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class TableAlias < Arel::Nodes::Binary
-
1
alias :name :right
-
1
alias :relation :left
-
1
alias :table_alias :name
-
-
1
def [] name
-
Attribute.new(self, name)
-
end
-
-
1
def table_name
-
relation.respond_to?(:name) ? relation.name : name
-
end
-
-
1
def engine
-
relation.engine
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Distinct < Arel::Nodes::Node
-
1
def hash
-
self.class.hash
-
end
-
-
1
def eql? other
-
self.class == other.class
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class True < Arel::Nodes::Node
-
1
def hash
-
self.class.hash
-
end
-
-
1
def eql? other
-
self.class == other.class
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Unary < Arel::Nodes::Node
-
1
attr_accessor :expr
-
1
alias :value :expr
-
-
1
def initialize expr
-
@expr = expr
-
end
-
-
1
def hash
-
@expr.hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.expr == other.expr
-
end
-
1
alias :== :eql?
-
end
-
-
%w{
-
Bin
-
1
Group
-
Having
-
Limit
-
Not
-
Offset
-
On
-
Ordering
-
Top
-
Lock
-
DistinctOn
-
}.each do |name|
-
11
const_set(name, Class.new(Unary))
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class UnqualifiedColumn < Arel::Nodes::Unary
-
1
alias :attribute :expr
-
1
alias :attribute= :expr=
-
-
1
def relation
-
@expr.relation
-
end
-
-
1
def column
-
@expr.column
-
end
-
-
1
def name
-
@expr.name
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class UpdateStatement < Arel::Nodes::Node
-
1
attr_accessor :relation, :wheres, :values, :orders, :limit
-
1
attr_accessor :key
-
-
1
def initialize
-
@relation = nil
-
@wheres = []
-
@values = []
-
@orders = []
-
@limit = nil
-
@key = nil
-
end
-
-
1
def initialize_copy other
-
super
-
@wheres = @wheres.clone
-
@values = @values.clone
-
end
-
-
1
def hash
-
[@relation, @wheres, @values, @orders, @limit, @key].hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.relation == other.relation &&
-
self.wheres == other.wheres &&
-
self.values == other.values &&
-
self.orders == other.orders &&
-
self.limit == other.limit &&
-
self.key == other.key
-
end
-
1
alias :== :eql?
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class Values < Arel::Nodes::Binary
-
1
alias :expressions :left
-
1
alias :expressions= :left=
-
1
alias :columns :right
-
1
alias :columns= :right=
-
-
1
def initialize exprs, columns = []
-
super
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Nodes
-
1
class With < Arel::Nodes::Unary
-
1
alias children expr
-
end
-
-
1
class WithRecursive < With; end
-
end
-
end
-
-
1
module Arel
-
1
module OrderPredications
-
-
1
def asc
-
Nodes::Ascending.new self
-
end
-
-
1
def desc
-
Nodes::Descending.new self
-
end
-
-
end
-
end
-
1
module Arel
-
1
module Predications
-
1
def not_eq other
-
Nodes::NotEqual.new self, other
-
end
-
-
1
def not_eq_any others
-
grouping_any :not_eq, others
-
end
-
-
1
def not_eq_all others
-
grouping_all :not_eq, others
-
end
-
-
1
def eq other
-
Nodes::Equality.new self, other
-
end
-
-
1
def eq_any others
-
grouping_any :eq, others
-
end
-
-
1
def eq_all others
-
grouping_all :eq, others
-
end
-
-
1
def in other
-
case other
-
when Arel::SelectManager
-
Arel::Nodes::In.new(self, other.ast)
-
when Range
-
if other.exclude_end?
-
left = Nodes::GreaterThanOrEqual.new(self, other.begin)
-
right = Nodes::LessThan.new(self, other.end)
-
Nodes::And.new [left, right]
-
else
-
Nodes::Between.new(self, Nodes::And.new([other.begin, other.end]))
-
end
-
else
-
Nodes::In.new self, other
-
end
-
end
-
-
1
def in_any others
-
grouping_any :in, others
-
end
-
-
1
def in_all others
-
grouping_all :in, others
-
end
-
-
1
def not_in other
-
case other
-
when Arel::SelectManager
-
Arel::Nodes::NotIn.new(self, other.ast)
-
when Range
-
if other.exclude_end?
-
left = Nodes::LessThan.new(self, other.begin)
-
right = Nodes::GreaterThanOrEqual.new(self, other.end)
-
Nodes::Or.new left, right
-
else
-
left = Nodes::LessThan.new(self, other.begin)
-
right = Nodes::GreaterThan.new(self, other.end)
-
Nodes::Or.new left, right
-
end
-
else
-
Nodes::NotIn.new self, other
-
end
-
end
-
-
1
def not_in_any others
-
grouping_any :not_in, others
-
end
-
-
1
def not_in_all others
-
grouping_all :not_in, others
-
end
-
-
1
def matches other
-
Nodes::Matches.new self, other
-
end
-
-
1
def matches_any others
-
grouping_any :matches, others
-
end
-
-
1
def matches_all others
-
grouping_all :matches, others
-
end
-
-
1
def does_not_match other
-
Nodes::DoesNotMatch.new self, other
-
end
-
-
1
def does_not_match_any others
-
grouping_any :does_not_match, others
-
end
-
-
1
def does_not_match_all others
-
grouping_all :does_not_match, others
-
end
-
-
1
def gteq right
-
Nodes::GreaterThanOrEqual.new self, right
-
end
-
-
1
def gteq_any others
-
grouping_any :gteq, others
-
end
-
-
1
def gteq_all others
-
grouping_all :gteq, others
-
end
-
-
1
def gt right
-
Nodes::GreaterThan.new self, right
-
end
-
-
1
def gt_any others
-
grouping_any :gt, others
-
end
-
-
1
def gt_all others
-
grouping_all :gt, others
-
end
-
-
1
def lt right
-
Nodes::LessThan.new self, right
-
end
-
-
1
def lt_any others
-
grouping_any :lt, others
-
end
-
-
1
def lt_all others
-
grouping_all :lt, others
-
end
-
-
1
def lteq right
-
Nodes::LessThanOrEqual.new self, right
-
end
-
-
1
def lteq_any others
-
grouping_any :lteq, others
-
end
-
-
1
def lteq_all others
-
grouping_all :lteq, others
-
end
-
-
1
private
-
-
1
def grouping_any method_id, others
-
nodes = others.map {|expr| send(method_id, expr)}
-
Nodes::Grouping.new nodes.inject { |memo,node|
-
Nodes::Or.new(memo, node)
-
}
-
end
-
-
1
def grouping_all method_id, others
-
Nodes::Grouping.new Nodes::And.new(others.map {|expr| send(method_id, expr)})
-
end
-
end
-
end
-
1
module Arel
-
1
class SelectManager < Arel::TreeManager
-
1
include Arel::Crud
-
-
1
def initialize engine, table = nil
-
super(engine)
-
@ast = Nodes::SelectStatement.new
-
@ctx = @ast.cores.last
-
from table
-
end
-
-
1
def initialize_copy other
-
super
-
@ctx = @ast.cores.last
-
end
-
-
1
def limit
-
@ast.limit && @ast.limit.expr
-
end
-
1
alias :taken :limit
-
-
1
def constraints
-
@ctx.wheres
-
end
-
-
1
def offset
-
@ast.offset && @ast.offset.expr
-
end
-
-
1
def skip amount
-
if amount
-
@ast.offset = Nodes::Offset.new(amount)
-
else
-
@ast.offset = nil
-
end
-
self
-
end
-
1
alias :offset= :skip
-
-
###
-
# Produces an Arel::Nodes::Exists node
-
1
def exists
-
Arel::Nodes::Exists.new @ast
-
end
-
-
1
def as other
-
create_table_alias grouping(@ast), Nodes::SqlLiteral.new(other)
-
end
-
-
1
def where_clauses
-
if $VERBOSE
-
warn "(#{caller.first}) where_clauses is deprecated and will be removed in arel 4.0.0 with no replacement"
-
end
-
to_sql = Visitors::ToSql.new @engine.connection
-
@ctx.wheres.map { |c| to_sql.accept c }
-
end
-
-
1
def lock locking = Arel.sql('FOR UPDATE')
-
case locking
-
when true
-
locking = Arel.sql('FOR UPDATE')
-
when Arel::Nodes::SqlLiteral
-
when String
-
locking = Arel.sql locking
-
end
-
-
@ast.lock = Nodes::Lock.new(locking)
-
self
-
end
-
-
1
def locked
-
@ast.lock
-
end
-
-
1
def on *exprs
-
@ctx.source.right.last.right = Nodes::On.new(collapse(exprs))
-
self
-
end
-
-
1
def group *columns
-
columns.each do |column|
-
# FIXME: backwards compat
-
column = Nodes::SqlLiteral.new(column) if String === column
-
column = Nodes::SqlLiteral.new(column.to_s) if Symbol === column
-
-
@ctx.groups.push Nodes::Group.new column
-
end
-
self
-
end
-
-
1
def from table
-
table = Nodes::SqlLiteral.new(table) if String === table
-
# FIXME: this is a hack to support
-
# test_with_two_tables_in_from_without_getting_double_quoted
-
# from the AR tests.
-
-
case table
-
when Nodes::Join
-
@ctx.source.right << table
-
else
-
@ctx.source.left = table
-
end
-
-
self
-
end
-
-
1
def froms
-
@ast.cores.map { |x| x.from }.compact
-
end
-
-
1
def join relation, klass = Nodes::InnerJoin
-
return self unless relation
-
-
case relation
-
when String, Nodes::SqlLiteral
-
raise if relation.blank?
-
klass = Nodes::StringJoin
-
end
-
-
@ctx.source.right << create_join(relation, nil, klass)
-
self
-
end
-
-
1
def having *exprs
-
@ctx.having = Nodes::Having.new(collapse(exprs, @ctx.having))
-
self
-
end
-
-
1
def window name
-
window = Nodes::NamedWindow.new(name)
-
@ctx.windows.push window
-
window
-
end
-
-
1
def project *projections
-
# FIXME: converting these to SQLLiterals is probably not good, but
-
# rails tests require it.
-
@ctx.projections.concat projections.map { |x|
-
[Symbol, String].include?(x.class) ? SqlLiteral.new(x.to_s) : x
-
}
-
self
-
end
-
-
1
def projections
-
@ctx.projections
-
end
-
-
1
def projections= projections
-
@ctx.projections = projections
-
end
-
-
1
def distinct(value = true)
-
if value
-
@ctx.set_quantifier = Arel::Nodes::Distinct.new
-
else
-
@ctx.set_quantifier = nil
-
end
-
end
-
-
1
def order *expr
-
# FIXME: We SHOULD NOT be converting these to SqlLiteral automatically
-
@ast.orders.concat expr.map { |x|
-
String === x || Symbol === x ? Nodes::SqlLiteral.new(x.to_s) : x
-
}
-
self
-
end
-
-
1
def orders
-
@ast.orders
-
end
-
-
1
def wheres
-
warn "#{caller[0]}: SelectManager#wheres is deprecated and will be removed in ARel 4.0.0 with no replacement"
-
Compatibility::Wheres.new @engine.connection, @ctx.wheres
-
end
-
-
1
def where_sql
-
return if @ctx.wheres.empty?
-
-
viz = Visitors::WhereSql.new @engine.connection
-
Nodes::SqlLiteral.new viz.accept @ctx
-
end
-
-
1
def union operation, other = nil
-
if other
-
node_class = Nodes.const_get("Union#{operation.to_s.capitalize}")
-
else
-
other = operation
-
node_class = Nodes::Union
-
end
-
-
node_class.new self.ast, other.ast
-
end
-
-
1
def intersect other
-
Nodes::Intersect.new ast, other.ast
-
end
-
-
1
def except other
-
Nodes::Except.new ast, other.ast
-
end
-
1
alias :minus :except
-
-
1
def with *subqueries
-
if subqueries.first.is_a? Symbol
-
node_class = Nodes.const_get("With#{subqueries.shift.to_s.capitalize}")
-
else
-
node_class = Nodes::With
-
end
-
@ast.with = node_class.new(subqueries.flatten)
-
-
self
-
end
-
-
1
def take limit
-
if limit
-
@ast.limit = Nodes::Limit.new(limit)
-
@ctx.top = Nodes::Top.new(limit)
-
else
-
@ast.limit = nil
-
@ctx.top = nil
-
end
-
self
-
end
-
1
alias limit= take
-
-
1
def join_sql
-
return nil if @ctx.source.right.empty?
-
-
sql = visitor.dup.extend(Visitors::JoinSql).accept @ctx
-
Nodes::SqlLiteral.new sql
-
end
-
-
1
def order_clauses
-
visitor = Visitors::OrderClauses.new(@engine.connection)
-
visitor.accept(@ast).map { |x|
-
Nodes::SqlLiteral.new x
-
}
-
end
-
-
1
def join_sources
-
@ctx.source.right
-
end
-
-
1
def source
-
@ctx.source
-
end
-
-
1
def joins manager
-
if $VERBOSE
-
warn "joins is deprecated and will be removed in 4.0.0"
-
warn "please remove your call to joins from #{caller.first}"
-
end
-
manager.join_sql
-
end
-
-
1
class Row < Struct.new(:data) # :nodoc:
-
1
def id
-
data['id']
-
end
-
-
1
def method_missing(name, *args)
-
name = name.to_s
-
return data[name] if data.key?(name)
-
super
-
end
-
end
-
-
1
def to_a # :nodoc:
-
warn "to_a is deprecated. Please remove it from #{caller[0]}"
-
# FIXME: I think `select` should be made public...
-
@engine.connection.send(:select, to_sql, 'AREL').map { |x| Row.new(x) }
-
end
-
-
# FIXME: this method should go away
-
1
def insert values
-
if $VERBOSE
-
warn <<-eowarn
-
insert (#{caller.first}) is deprecated and will be removed in ARel 4.0.0. Please
-
switch to `compile_insert`
-
eowarn
-
end
-
-
im = compile_insert(values)
-
table = @ctx.froms
-
-
primary_key = table.primary_key
-
primary_key_name = primary_key.name if primary_key
-
-
# FIXME: in AR tests values sometimes were Array and not Hash therefore is_a?(Hash) check is added
-
primary_key_value = primary_key && values.is_a?(Hash) && values[primary_key]
-
im.into table
-
# Oracle adapter needs primary key name to generate RETURNING ... INTO ... clause
-
# for tables which assign primary key value using trigger.
-
# RETURNING ... INTO ... clause will be added only if primary_key_value is nil
-
# therefore it is necessary to pass primary key value as well
-
@engine.connection.insert im.to_sql, 'AREL', primary_key_name, primary_key_value
-
end
-
-
1
private
-
1
def collapse exprs, existing = nil
-
exprs = exprs.unshift(existing.expr) if existing
-
exprs = exprs.compact.map { |expr|
-
if String === expr
-
# FIXME: Don't do this automatically
-
Arel.sql(expr)
-
else
-
expr
-
end
-
}
-
-
if exprs.length == 1
-
exprs.first
-
else
-
create_and exprs
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Sql
-
1
class Engine
-
1
def self.new thing
-
#warn "#{caller.first} -- Engine will be removed"
-
thing
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
class SqlLiteral < Nodes::SqlLiteral
-
end
-
end
-
1
module Arel
-
1
class Table
-
1
include Arel::Crud
-
1
include Arel::FactoryMethods
-
-
1
@engine = nil
-
2
class << self; attr_accessor :engine; end
-
-
1
attr_accessor :name, :engine, :aliases, :table_alias
-
-
# TableAlias and Table both have a #table_name which is the name of the underlying table
-
1
alias :table_name :name
-
-
1
def initialize name, engine = Table.engine
-
@name = name.to_s
-
@engine = engine
-
@columns = nil
-
@aliases = []
-
@table_alias = nil
-
@primary_key = nil
-
-
if Hash === engine
-
@engine = engine[:engine] || Table.engine
-
-
# Sometime AR sends an :as parameter to table, to let the table know
-
# that it is an Alias. We may want to override new, and return a
-
# TableAlias node?
-
@table_alias = engine[:as] unless engine[:as].to_s == @name
-
end
-
end
-
-
1
def primary_key
-
if $VERBOSE
-
warn <<-eowarn
-
primary_key (#{caller.first}) is deprecated and will be removed in ARel 4.0.0
-
eowarn
-
end
-
@primary_key ||= begin
-
primary_key_name = @engine.connection.primary_key(name)
-
# some tables might be without primary key
-
primary_key_name && self[primary_key_name]
-
end
-
end
-
-
1
def alias name = "#{self.name}_2"
-
Nodes::TableAlias.new(self, name).tap do |node|
-
@aliases << node
-
end
-
end
-
-
1
def from table
-
SelectManager.new(@engine, table)
-
end
-
-
1
def joins manager
-
if $VERBOSE
-
warn "joins is deprecated and will be removed in 4.0.0"
-
warn "please remove your call to joins from #{caller.first}"
-
end
-
nil
-
end
-
-
1
def join relation, klass = Nodes::InnerJoin
-
return from(self) unless relation
-
-
case relation
-
when String, Nodes::SqlLiteral
-
raise if relation.blank?
-
klass = Nodes::StringJoin
-
end
-
-
from(self).join(relation, klass)
-
end
-
-
1
def group *columns
-
from(self).group(*columns)
-
end
-
-
1
def order *expr
-
from(self).order(*expr)
-
end
-
-
1
def where condition
-
from(self).where condition
-
end
-
-
1
def project *things
-
from(self).project(*things)
-
end
-
-
1
def take amount
-
from(self).take amount
-
end
-
-
1
def skip amount
-
from(self).skip amount
-
end
-
-
1
def having expr
-
from(self).having expr
-
end
-
-
1
def columns
-
if $VERBOSE
-
warn <<-eowarn
-
(#{caller.first}) Arel::Table#columns is deprecated and will be removed in
-
Arel 4.0.0 with no replacement. PEW PEW PEW!!!
-
eowarn
-
end
-
@columns ||=
-
attributes_for @engine.connection.columns(@name, "#{@name} Columns")
-
end
-
-
1
def [] name
-
::Arel::Attribute.new self, name
-
end
-
-
1
def select_manager
-
SelectManager.new(@engine)
-
end
-
-
1
def insert_manager
-
InsertManager.new(@engine)
-
end
-
-
1
def hash
-
[@name, @engine, @aliases, @table_alias].hash
-
end
-
-
1
def eql? other
-
self.class == other.class &&
-
self.name == other.name &&
-
self.engine == other.engine &&
-
self.aliases == other.aliases &&
-
self.table_alias == other.table_alias
-
end
-
1
alias :== :eql?
-
-
1
private
-
-
1
def attributes_for columns
-
return nil unless columns
-
-
columns.map do |column|
-
Attributes.for(column).new self, column.name.to_sym
-
end
-
end
-
-
1
@@table_cache = nil
-
1
def self.table_cache engine # :nodoc:
-
if $VERBOSE
-
warn <<-eowarn
-
(#{caller.first}) Arel::Table.table_cache is deprecated and will be removed in
-
Arel 4.0.0 with no replacement. PEW PEW PEW!!!
-
eowarn
-
end
-
@@table_cache ||= Hash[engine.connection.tables.map { |x| [x,true] }]
-
end
-
end
-
end
-
1
module Arel
-
1
class TreeManager
-
1
include Arel::FactoryMethods
-
-
1
attr_reader :ast, :engine
-
-
1
def initialize engine
-
@engine = engine
-
@ctx = nil
-
end
-
-
1
def to_dot
-
Visitors::Dot.new.accept @ast
-
end
-
-
1
def visitor
-
engine.connection.visitor
-
end
-
-
1
def to_sql
-
visitor.accept @ast
-
end
-
-
1
def initialize_copy other
-
super
-
@ast = @ast.clone
-
end
-
-
1
def where expr
-
if Arel::TreeManager === expr
-
expr = expr.ast
-
end
-
@ctx.wheres << expr
-
self
-
end
-
end
-
end
-
1
module Arel
-
1
class UpdateManager < Arel::TreeManager
-
1
def initialize engine
-
super
-
@ast = Nodes::UpdateStatement.new
-
@ctx = @ast
-
end
-
-
1
def take limit
-
@ast.limit = Nodes::Limit.new(limit) if limit
-
self
-
end
-
-
1
def key= key
-
@ast.key = key
-
end
-
-
1
def key
-
@ast.key
-
end
-
-
1
def order *expr
-
@ast.orders = expr
-
self
-
end
-
-
###
-
# UPDATE +table+
-
1
def table table
-
@ast.relation = table
-
self
-
end
-
-
1
def wheres= exprs
-
@ast.wheres = exprs
-
end
-
-
1
def where expr
-
@ast.wheres << expr
-
self
-
end
-
-
1
def set values
-
if String === values
-
@ast.values = [values]
-
else
-
@ast.values = values.map { |column,value|
-
Nodes::Assignment.new(
-
Nodes::UnqualifiedColumn.new(column),
-
value
-
)
-
}
-
end
-
self
-
end
-
end
-
end
-
1
require 'arel/visitors/visitor'
-
1
require 'arel/visitors/depth_first'
-
1
require 'arel/visitors/to_sql'
-
1
require 'arel/visitors/sqlite'
-
1
require 'arel/visitors/postgresql'
-
1
require 'arel/visitors/mysql'
-
1
require 'arel/visitors/mssql'
-
1
require 'arel/visitors/oracle'
-
1
require 'arel/visitors/join_sql'
-
1
require 'arel/visitors/where_sql'
-
1
require 'arel/visitors/order_clauses'
-
1
require 'arel/visitors/dot'
-
1
require 'arel/visitors/ibm_db'
-
1
require 'arel/visitors/informix'
-
-
1
module Arel
-
1
module Visitors
-
1
VISITORS = {
-
'postgresql' => Arel::Visitors::PostgreSQL,
-
'mysql' => Arel::Visitors::MySQL,
-
'mysql2' => Arel::Visitors::MySQL,
-
'mssql' => Arel::Visitors::MSSQL,
-
'sqlserver' => Arel::Visitors::MSSQL,
-
'oracle_enhanced' => Arel::Visitors::Oracle,
-
'sqlite' => Arel::Visitors::SQLite,
-
'sqlite3' => Arel::Visitors::SQLite,
-
'ibm_db' => Arel::Visitors::IBM_DB,
-
'informix' => Arel::Visitors::Informix,
-
}
-
-
1
ENGINE_VISITORS = Hash.new do |hash, engine|
-
pool = engine.connection_pool
-
adapter = pool.spec.config[:adapter]
-
hash[engine] = (VISITORS[adapter] || Visitors::ToSql).new(engine)
-
end
-
-
1
def self.visitor_for engine
-
ENGINE_VISITORS[engine]
-
end
-
2
class << self; alias :for :visitor_for; end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class Dot < Arel::Visitors::Visitor
-
1
class Node # :nodoc:
-
1
attr_accessor :name, :id, :fields
-
-
1
def initialize name, id, fields = []
-
@name = name
-
@id = id
-
@fields = fields
-
end
-
end
-
-
1
class Edge < Struct.new :name, :from, :to # :nodoc:
-
end
-
-
1
def initialize
-
@nodes = []
-
@edges = []
-
@node_stack = []
-
@edge_stack = []
-
@seen = {}
-
end
-
-
1
def accept object
-
super
-
to_dot
-
end
-
-
1
private
-
1
def visit_Arel_Nodes_Ordering o
-
visit_edge o, "expr"
-
end
-
-
1
def visit_Arel_Nodes_TableAlias o
-
visit_edge o, "name"
-
visit_edge o, "relation"
-
end
-
-
1
def visit_Arel_Nodes_Count o
-
visit_edge o, "expressions"
-
visit_edge o, "distinct"
-
end
-
-
1
def visit_Arel_Nodes_Values o
-
visit_edge o, "expressions"
-
end
-
-
1
def visit_Arel_Nodes_StringJoin o
-
visit_edge o, "left"
-
end
-
-
1
def visit_Arel_Nodes_InnerJoin o
-
visit_edge o, "left"
-
visit_edge o, "right"
-
end
-
1
alias :visit_Arel_Nodes_OuterJoin :visit_Arel_Nodes_InnerJoin
-
-
1
def visit_Arel_Nodes_DeleteStatement o
-
visit_edge o, "relation"
-
visit_edge o, "wheres"
-
end
-
-
1
def unary o
-
visit_edge o, "expr"
-
end
-
1
alias :visit_Arel_Nodes_Group :unary
-
1
alias :visit_Arel_Nodes_BindParam :unary
-
1
alias :visit_Arel_Nodes_Grouping :unary
-
1
alias :visit_Arel_Nodes_Having :unary
-
1
alias :visit_Arel_Nodes_Limit :unary
-
1
alias :visit_Arel_Nodes_Not :unary
-
1
alias :visit_Arel_Nodes_Offset :unary
-
1
alias :visit_Arel_Nodes_On :unary
-
1
alias :visit_Arel_Nodes_Top :unary
-
1
alias :visit_Arel_Nodes_UnqualifiedColumn :unary
-
1
alias :visit_Arel_Nodes_Preceding :unary
-
1
alias :visit_Arel_Nodes_Following :unary
-
1
alias :visit_Arel_Nodes_Rows :unary
-
1
alias :visit_Arel_Nodes_Range :unary
-
-
1
def window o
-
visit_edge o, "orders"
-
visit_edge o, "framing"
-
end
-
1
alias :visit_Arel_Nodes_Window :window
-
-
1
def named_window o
-
visit_edge o, "orders"
-
visit_edge o, "framing"
-
visit_edge o, "name"
-
end
-
1
alias :visit_Arel_Nodes_NamedWindow :named_window
-
-
1
def function o
-
visit_edge o, "expressions"
-
visit_edge o, "distinct"
-
visit_edge o, "alias"
-
end
-
1
alias :visit_Arel_Nodes_Exists :function
-
1
alias :visit_Arel_Nodes_Min :function
-
1
alias :visit_Arel_Nodes_Max :function
-
1
alias :visit_Arel_Nodes_Avg :function
-
1
alias :visit_Arel_Nodes_Sum :function
-
-
1
def extract o
-
visit_edge o, "expressions"
-
visit_edge o, "alias"
-
end
-
1
alias :visit_Arel_Nodes_Extract :extract
-
-
1
def visit_Arel_Nodes_NamedFunction o
-
visit_edge o, "name"
-
visit_edge o, "expressions"
-
visit_edge o, "distinct"
-
visit_edge o, "alias"
-
end
-
-
1
def visit_Arel_Nodes_InsertStatement o
-
visit_edge o, "relation"
-
visit_edge o, "columns"
-
visit_edge o, "values"
-
end
-
-
1
def visit_Arel_Nodes_SelectCore o
-
visit_edge o, "source"
-
visit_edge o, "projections"
-
visit_edge o, "wheres"
-
visit_edge o, "windows"
-
end
-
-
1
def visit_Arel_Nodes_SelectStatement o
-
visit_edge o, "cores"
-
visit_edge o, "limit"
-
visit_edge o, "orders"
-
visit_edge o, "offset"
-
end
-
-
1
def visit_Arel_Nodes_UpdateStatement o
-
visit_edge o, "relation"
-
visit_edge o, "wheres"
-
visit_edge o, "values"
-
end
-
-
1
def visit_Arel_Table o
-
visit_edge o, "name"
-
end
-
-
1
def visit_Arel_Attribute o
-
visit_edge o, "relation"
-
visit_edge o, "name"
-
end
-
1
alias :visit_Arel_Attributes_Integer :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_Float :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_String :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_Time :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_Boolean :visit_Arel_Attribute
-
1
alias :visit_Arel_Attributes_Attribute :visit_Arel_Attribute
-
-
1
def nary o
-
o.children.each_with_index do |x,i|
-
edge(i) { visit x }
-
end
-
end
-
1
alias :visit_Arel_Nodes_And :nary
-
-
1
def binary o
-
visit_edge o, "left"
-
visit_edge o, "right"
-
end
-
1
alias :visit_Arel_Nodes_As :binary
-
1
alias :visit_Arel_Nodes_Assignment :binary
-
1
alias :visit_Arel_Nodes_Between :binary
-
1
alias :visit_Arel_Nodes_DoesNotMatch :binary
-
1
alias :visit_Arel_Nodes_Equality :binary
-
1
alias :visit_Arel_Nodes_GreaterThan :binary
-
1
alias :visit_Arel_Nodes_GreaterThanOrEqual :binary
-
1
alias :visit_Arel_Nodes_In :binary
-
1
alias :visit_Arel_Nodes_JoinSource :binary
-
1
alias :visit_Arel_Nodes_LessThan :binary
-
1
alias :visit_Arel_Nodes_LessThanOrEqual :binary
-
1
alias :visit_Arel_Nodes_Matches :binary
-
1
alias :visit_Arel_Nodes_NotEqual :binary
-
1
alias :visit_Arel_Nodes_NotIn :binary
-
1
alias :visit_Arel_Nodes_Or :binary
-
1
alias :visit_Arel_Nodes_Over :binary
-
-
1
def visit_String o
-
@node_stack.last.fields << o
-
end
-
1
alias :visit_Time :visit_String
-
1
alias :visit_Date :visit_String
-
1
alias :visit_DateTime :visit_String
-
1
alias :visit_NilClass :visit_String
-
1
alias :visit_TrueClass :visit_String
-
1
alias :visit_FalseClass :visit_String
-
1
alias :visit_Arel_SqlLiteral :visit_String
-
1
alias :visit_Fixnum :visit_String
-
1
alias :visit_BigDecimal :visit_String
-
1
alias :visit_Float :visit_String
-
1
alias :visit_Symbol :visit_String
-
1
alias :visit_Arel_Nodes_SqlLiteral :visit_String
-
-
1
def visit_Hash o
-
o.each_with_index do |pair, i|
-
edge("pair_#{i}") { visit pair }
-
end
-
end
-
-
1
def visit_Array o
-
o.each_with_index do |x,i|
-
edge(i) { visit x }
-
end
-
end
-
-
1
def visit_edge o, method
-
edge(method) { visit o.send(method) }
-
end
-
-
1
def visit o
-
if node = @seen[o.object_id]
-
@edge_stack.last.to = node
-
return
-
end
-
-
node = Node.new(o.class.name, o.object_id)
-
@seen[node.id] = node
-
@nodes << node
-
with_node node do
-
super
-
end
-
end
-
-
1
def edge name
-
edge = Edge.new(name, @node_stack.last)
-
@edge_stack.push edge
-
@edges << edge
-
yield
-
@edge_stack.pop
-
end
-
-
1
def with_node node
-
if edge = @edge_stack.last
-
edge.to = node
-
end
-
-
@node_stack.push node
-
yield
-
@node_stack.pop
-
end
-
-
1
def quote string
-
string.to_s.gsub('"', '\"')
-
end
-
-
1
def to_dot
-
"digraph \"ARel\" {\nnode [width=0.375,height=0.25,shape=record];\n" +
-
@nodes.map { |node|
-
label = "<f0>#{node.name}"
-
-
node.fields.each_with_index do |field, i|
-
label << "|<f#{i + 1}>#{quote field}"
-
end
-
-
"#{node.id} [label=\"#{label}\"];"
-
}.join("\n") + "\n" + @edges.map { |edge|
-
"#{edge.from.id} -> #{edge.to.id} [label=\"#{edge.name}\"];"
-
}.join("\n") + "\n}"
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class IBM_DB < Arel::Visitors::ToSql
-
1
private
-
-
1
def visit_Arel_Nodes_Limit o
-
"FETCH FIRST #{visit o.expr} ROWS ONLY"
-
end
-
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class Informix < Arel::Visitors::ToSql
-
1
private
-
1
def visit_Arel_Nodes_SelectStatement o
-
[
-
"SELECT",
-
(visit(o.offset) if o.offset),
-
(visit(o.limit) if o.limit),
-
o.cores.map { |x| visit_Arel_Nodes_SelectCore x }.join,
-
("ORDER BY #{o.orders.map { |x| visit x }.join(', ')}" unless o.orders.empty?),
-
(visit(o.lock) if o.lock),
-
].compact.join ' '
-
end
-
1
def visit_Arel_Nodes_SelectCore o
-
[
-
"#{o.projections.map { |x| visit x }.join ', '}",
-
("FROM #{visit(o.source)}" if o.source && !o.source.empty?),
-
("WHERE #{o.wheres.map { |x| visit x }.join ' AND ' }" unless o.wheres.empty?),
-
("GROUP BY #{o.groups.map { |x| visit x }.join ', ' }" unless o.groups.empty?),
-
(visit(o.having) if o.having),
-
].compact.join ' '
-
end
-
1
def visit_Arel_Nodes_Offset o
-
"SKIP #{visit o.expr}"
-
end
-
1
def visit_Arel_Nodes_Limit o
-
"LIMIT #{visit o.expr}"
-
end
-
end
-
end
-
end
-
-
1
module Arel
-
1
module Visitors
-
###
-
# This class produces SQL for JOIN clauses but omits the "single-source"
-
# part of the Join grammar:
-
#
-
# http://www.sqlite.org/syntaxdiagrams.html#join-source
-
#
-
# This visitor is used in SelectManager#join_sql and is for backwards
-
# compatibility with Arel V1.0
-
1
module JoinSql
-
1
private
-
-
1
def visit_Arel_Nodes_SelectCore o
-
o.source.right.map { |j| visit j }.join ' '
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class MSSQL < Arel::Visitors::ToSql
-
1
private
-
-
# `top` wouldn't really work here. I.e. User.select("distinct first_name").limit(10) would generate
-
# "select top 10 distinct first_name from users", which is invalid query! it should be
-
# "select distinct top 10 first_name from users"
-
1
def visit_Arel_Nodes_Top o
-
""
-
end
-
-
1
def visit_Arel_Nodes_SelectStatement o
-
if !o.limit && !o.offset
-
return super o
-
end
-
-
select_order_by = "ORDER BY #{o.orders.map { |x| visit x }.join(', ')}" unless o.orders.empty?
-
-
is_select_count = false
-
sql = o.cores.map { |x|
-
core_order_by = select_order_by || determine_order_by(x)
-
if select_count? x
-
x.projections = [row_num_literal(core_order_by)]
-
is_select_count = true
-
else
-
x.projections << row_num_literal(core_order_by)
-
end
-
-
visit_Arel_Nodes_SelectCore x
-
}.join
-
-
sql = "SELECT _t.* FROM (#{sql}) as _t WHERE #{get_offset_limit_clause(o)}"
-
# fixme count distinct wouldn't work with limit or offset
-
sql = "SELECT COUNT(1) as count_id FROM (#{sql}) AS subquery" if is_select_count
-
sql
-
end
-
-
1
def get_offset_limit_clause o
-
first_row = o.offset ? o.offset.expr.to_i + 1 : 1
-
last_row = o.limit ? o.limit.expr.to_i - 1 + first_row : nil
-
if last_row
-
" _row_num BETWEEN #{first_row} AND #{last_row}"
-
else
-
" _row_num >= #{first_row}"
-
end
-
end
-
-
1
def determine_order_by x
-
unless x.groups.empty?
-
"ORDER BY #{x.groups.map { |g| visit g }.join ', ' }"
-
else
-
"ORDER BY #{find_left_table_pk(x.froms)}"
-
end
-
end
-
-
1
def row_num_literal order_by
-
Nodes::SqlLiteral.new("ROW_NUMBER() OVER (#{order_by}) as _row_num")
-
end
-
-
1
def select_count? x
-
x.projections.length == 1 && Arel::Nodes::Count === x.projections.first
-
end
-
-
# fixme raise exception of there is no pk?
-
# fixme!! Table.primary_key will be depricated. What is the replacement??
-
1
def find_left_table_pk o
-
return visit o.primary_key if o.instance_of? Arel::Table
-
find_left_table_pk o.left if o.kind_of? Arel::Nodes::Join
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class MySQL < Arel::Visitors::ToSql
-
1
private
-
1
def visit_Arel_Nodes_Union o, suppress_parens = false
-
left_result = case o.left
-
when Arel::Nodes::Union
-
visit_Arel_Nodes_Union o.left, true
-
else
-
visit o.left
-
end
-
-
right_result = case o.right
-
when Arel::Nodes::Union
-
visit_Arel_Nodes_Union o.right, true
-
else
-
visit o.right
-
end
-
-
if suppress_parens
-
"#{left_result} UNION #{right_result}"
-
else
-
"( #{left_result} UNION #{right_result} )"
-
end
-
end
-
-
1
def visit_Arel_Nodes_Bin o
-
"BINARY #{visit o.expr}"
-
end
-
-
###
-
# :'(
-
# http://dev.mysql.com/doc/refman/5.0/en/select.html#id3482214
-
1
def visit_Arel_Nodes_SelectStatement o
-
o.limit = Arel::Nodes::Limit.new(18446744073709551615) if o.offset && !o.limit
-
super
-
end
-
-
1
def visit_Arel_Nodes_SelectCore o
-
o.froms ||= Arel.sql('DUAL')
-
super
-
end
-
-
1
def visit_Arel_Nodes_UpdateStatement o
-
[
-
"UPDATE #{visit o.relation}",
-
("SET #{o.values.map { |value| visit value }.join ', '}" unless o.values.empty?),
-
("WHERE #{o.wheres.map { |x| visit x }.join ' AND '}" unless o.wheres.empty?),
-
("ORDER BY #{o.orders.map { |x| visit x }.join(', ')}" unless o.orders.empty?),
-
(visit(o.limit) if o.limit),
-
].compact.join ' '
-
end
-
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class Oracle < Arel::Visitors::ToSql
-
1
private
-
-
1
def visit_Arel_Nodes_SelectStatement o
-
o = order_hacks(o)
-
-
# if need to select first records without ORDER BY and GROUP BY and without DISTINCT
-
# then can use simple ROWNUM in WHERE clause
-
if o.limit && o.orders.empty? && !o.offset && o.cores.first.projections.first !~ /^DISTINCT /
-
o.cores.last.wheres.push Nodes::LessThanOrEqual.new(
-
Nodes::SqlLiteral.new('ROWNUM'), o.limit.expr
-
)
-
return super
-
end
-
-
if o.limit && o.offset
-
o = o.dup
-
limit = o.limit.expr.to_i
-
offset = o.offset
-
o.offset = nil
-
sql = super(o)
-
return <<-eosql
-
SELECT * FROM (
-
SELECT raw_sql_.*, rownum raw_rnum_
-
FROM (#{sql}) raw_sql_
-
)
-
WHERE raw_rnum_ between #{offset.expr.to_i + 1 } and #{offset.expr.to_i + limit}
-
eosql
-
end
-
-
if o.limit
-
o = o.dup
-
limit = o.limit.expr
-
return "SELECT * FROM (#{super(o)}) WHERE ROWNUM <= #{visit limit}"
-
end
-
-
if o.offset
-
o = o.dup
-
offset = o.offset
-
o.offset = nil
-
sql = super(o)
-
return <<-eosql
-
SELECT * FROM (
-
SELECT raw_sql_.*, rownum raw_rnum_
-
FROM (#{sql}) raw_sql_
-
)
-
WHERE #{visit offset}
-
eosql
-
end
-
-
super
-
end
-
-
1
def visit_Arel_Nodes_Limit o
-
end
-
-
1
def visit_Arel_Nodes_Offset o
-
"raw_rnum_ > #{visit o.expr}"
-
end
-
-
1
def visit_Arel_Nodes_Except o
-
"( #{visit o.left} MINUS #{visit o.right} )"
-
end
-
-
1
def visit_Arel_Nodes_UpdateStatement o
-
# Oracle does not allow ORDER BY/LIMIT in UPDATEs.
-
if o.orders.any? && o.limit.nil?
-
# However, there is no harm in silently eating the ORDER BY clause if no LIMIT has been provided,
-
# otherwise let the user deal with the error
-
o = o.dup
-
o.orders = []
-
end
-
-
super
-
end
-
-
###
-
# Hacks for the order clauses specific to Oracle
-
1
def order_hacks o
-
return o if o.orders.empty?
-
return o unless o.cores.any? do |core|
-
core.projections.any? do |projection|
-
/DISTINCT.*FIRST_VALUE/ === projection
-
end
-
end
-
# Previous version with join and split broke ORDER BY clause
-
# if it contained functions with several arguments (separated by ',').
-
#
-
# orders = o.orders.map { |x| visit x }.join(', ').split(',')
-
orders = o.orders.map do |x|
-
string = visit x
-
if string.include?(',')
-
split_order_string(string)
-
else
-
string
-
end
-
end.flatten
-
o.orders = []
-
orders.each_with_index do |order, i|
-
o.orders <<
-
Nodes::SqlLiteral.new("alias_#{i}__#{' DESC' if /\bdesc$/i === order}")
-
end
-
o
-
end
-
-
# Split string by commas but count opening and closing brackets
-
# and ignore commas inside brackets.
-
1
def split_order_string(string)
-
array = []
-
i = 0
-
string.split(',').each do |part|
-
if array[i]
-
array[i] << ',' << part
-
else
-
# to ensure that array[i] will be String and not Arel::Nodes::SqlLiteral
-
array[i] = '' << part
-
end
-
i += 1 if array[i].count('(') == array[i].count(')')
-
end
-
array
-
end
-
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class OrderClauses < Arel::Visitors::ToSql
-
1
private
-
-
1
def visit_Arel_Nodes_SelectStatement o
-
o.orders.map { |x| visit x }
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class PostgreSQL < Arel::Visitors::ToSql
-
1
private
-
-
1
def visit_Arel_Nodes_Matches o
-
"#{visit o.left} ILIKE #{visit o.right}"
-
end
-
-
1
def visit_Arel_Nodes_DoesNotMatch o
-
"#{visit o.left} NOT ILIKE #{visit o.right}"
-
end
-
-
1
def visit_Arel_Nodes_DistinctOn o
-
"DISTINCT ON ( #{visit o.expr} )"
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class SQLite < Arel::Visitors::ToSql
-
1
private
-
-
# Locks are not supported in SQLite
-
1
def visit_Arel_Nodes_Lock o
-
end
-
-
1
def visit_Arel_Nodes_SelectStatement o
-
o.limit = Arel::Nodes::Limit.new(-1) if o.offset && !o.limit
-
super
-
end
-
end
-
end
-
end
-
1
require 'bigdecimal'
-
1
require 'date'
-
-
1
module Arel
-
1
module Visitors
-
1
class ToSql < Arel::Visitors::Visitor
-
##
-
# This is some roflscale crazy stuff. I'm roflscaling this because
-
# building SQL queries is a hotspot. I will explain the roflscale so that
-
# others will not rm this code.
-
#
-
# In YARV, string literals in a method body will get duped when the byte
-
# code is executed. Let's take a look:
-
#
-
# > puts RubyVM::InstructionSequence.new('def foo; "bar"; end').disasm
-
#
-
# == disasm: <RubyVM::InstructionSequence:foo@<compiled>>=====
-
# 0000 trace 8
-
# 0002 trace 1
-
# 0004 putstring "bar"
-
# 0006 trace 16
-
# 0008 leave
-
#
-
# The `putstring` bytecode will dup the string and push it on the stack.
-
# In many cases in our SQL visitor, that string is never mutated, so there
-
# is no need to dup the literal.
-
#
-
# If we change to a constant lookup, the string will not be duped, and we
-
# can reduce the objects in our system:
-
#
-
# > puts RubyVM::InstructionSequence.new('BAR = "bar"; def foo; BAR; end').disasm
-
#
-
# == disasm: <RubyVM::InstructionSequence:foo@<compiled>>========
-
# 0000 trace 8
-
# 0002 trace 1
-
# 0004 getinlinecache 11, <ic:0>
-
# 0007 getconstant :BAR
-
# 0009 setinlinecache <ic:0>
-
# 0011 trace 16
-
# 0013 leave
-
#
-
# `getconstant` should be a hash lookup, and no object is duped when the
-
# value of the constant is pushed on the stack. Hence the crazy
-
# constants below.
-
-
1
WHERE = ' WHERE ' # :nodoc:
-
1
SPACE = ' ' # :nodoc:
-
1
COMMA = ', ' # :nodoc:
-
1
GROUP_BY = ' GROUP BY ' # :nodoc:
-
1
ORDER_BY = ' ORDER BY ' # :nodoc:
-
1
WINDOW = ' WINDOW ' # :nodoc:
-
1
AND = ' AND ' # :nodoc:
-
-
1
DISTINCT = 'DISTINCT' # :nodoc:
-
-
1
attr_accessor :last_column
-
-
1
def initialize connection
-
@connection = connection
-
@schema_cache = connection.schema_cache
-
@quoted_tables = {}
-
@quoted_columns = {}
-
@last_column = nil
-
end
-
-
1
def accept object
-
self.last_column = nil
-
super
-
end
-
-
1
private
-
1
def visit_Arel_Nodes_DeleteStatement o
-
[
-
"DELETE FROM #{visit o.relation}",
-
("WHERE #{o.wheres.map { |x| visit x }.join AND}" unless o.wheres.empty?)
-
].compact.join ' '
-
end
-
-
# FIXME: we should probably have a 2-pass visitor for this
-
1
def build_subselect key, o
-
stmt = Nodes::SelectStatement.new
-
core = stmt.cores.first
-
core.froms = o.relation
-
core.wheres = o.wheres
-
core.projections = [key]
-
stmt.limit = o.limit
-
stmt.orders = o.orders
-
stmt
-
end
-
-
1
def visit_Arel_Nodes_UpdateStatement o
-
if o.orders.empty? && o.limit.nil?
-
wheres = o.wheres
-
else
-
key = o.key
-
unless key
-
warn(<<-eowarn) if $VERBOSE
-
(#{caller.first}) Using UpdateManager without setting UpdateManager#key is
-
deprecated and support will be removed in ARel 4.0.0. Please set the primary
-
key on UpdateManager using UpdateManager#key=
-
eowarn
-
key = o.relation.primary_key
-
end
-
-
wheres = [Nodes::In.new(key, [build_subselect(key, o)])]
-
end
-
-
[
-
"UPDATE #{visit o.relation}",
-
("SET #{o.values.map { |value| visit value }.join ', '}" unless o.values.empty?),
-
("WHERE #{wheres.map { |x| visit x }.join ' AND '}" unless wheres.empty?),
-
].compact.join ' '
-
end
-
-
1
def visit_Arel_Nodes_InsertStatement o
-
[
-
"INSERT INTO #{visit o.relation}",
-
-
("(#{o.columns.map { |x|
-
quote_column_name x.name
-
}.join ', '})" unless o.columns.empty?),
-
-
(visit o.values if o.values),
-
].compact.join ' '
-
end
-
-
1
def visit_Arel_Nodes_Exists o
-
"EXISTS (#{visit o.expressions})#{
-
o.alias ? " AS #{visit o.alias}" : ''}"
-
end
-
-
1
def visit_Arel_Nodes_True o
-
"TRUE"
-
end
-
-
1
def visit_Arel_Nodes_False o
-
"FALSE"
-
end
-
-
1
def table_exists? name
-
@schema_cache.table_exists? name
-
end
-
-
1
def column_for attr
-
name = attr.name.to_s
-
table = attr.relation.table_name
-
-
return nil unless table_exists? table
-
-
column_cache[table][name]
-
end
-
-
1
def column_cache
-
@schema_cache.columns_hash
-
end
-
-
1
def visit_Arel_Nodes_Values o
-
"VALUES (#{o.expressions.zip(o.columns).map { |value, attr|
-
if Nodes::SqlLiteral === value
-
visit value
-
else
-
quote(value, attr && column_for(attr))
-
end
-
}.join ', '})"
-
end
-
-
1
def visit_Arel_Nodes_SelectStatement o
-
str = ''
-
-
if o.with
-
str << visit(o.with)
-
str << SPACE
-
end
-
-
o.cores.each { |x| str << visit_Arel_Nodes_SelectCore(x) }
-
-
unless o.orders.empty?
-
str << SPACE
-
str << ORDER_BY
-
len = o.orders.length - 1
-
o.orders.each_with_index { |x, i|
-
str << visit(x)
-
str << COMMA unless len == i
-
}
-
end
-
-
str << " #{visit(o.limit)}" if o.limit
-
str << " #{visit(o.offset)}" if o.offset
-
str << " #{visit(o.lock)}" if o.lock
-
-
str.strip!
-
str
-
end
-
-
1
def visit_Arel_Nodes_SelectCore o
-
str = "SELECT"
-
-
str << " #{visit(o.top)}" if o.top
-
str << " #{visit(o.set_quantifier)}" if o.set_quantifier
-
-
unless o.projections.empty?
-
str << SPACE
-
len = o.projections.length - 1
-
o.projections.each_with_index do |x, i|
-
str << visit(x)
-
str << COMMA unless len == i
-
end
-
end
-
-
str << " FROM #{visit(o.source)}" if o.source && !o.source.empty?
-
-
unless o.wheres.empty?
-
str << WHERE
-
len = o.wheres.length - 1
-
o.wheres.each_with_index do |x, i|
-
str << visit(x)
-
str << AND unless len == i
-
end
-
end
-
-
unless o.groups.empty?
-
str << GROUP_BY
-
len = o.groups.length - 1
-
o.groups.each_with_index do |x, i|
-
str << visit(x)
-
str << COMMA unless len == i
-
end
-
end
-
-
str << " #{visit(o.having)}" if o.having
-
-
unless o.windows.empty?
-
str << WINDOW
-
len = o.windows.length - 1
-
o.windows.each_with_index do |x, i|
-
str << visit(x)
-
str << COMMA unless len == i
-
end
-
end
-
-
str
-
end
-
-
1
def visit_Arel_Nodes_Bin o
-
visit o.expr
-
end
-
-
1
def visit_Arel_Nodes_Distinct o
-
DISTINCT
-
end
-
-
1
def visit_Arel_Nodes_DistinctOn o
-
raise NotImplementedError, 'DISTINCT ON not implemented for this db'
-
end
-
-
1
def visit_Arel_Nodes_With o
-
"WITH #{o.children.map { |x| visit x }.join(', ')}"
-
end
-
-
1
def visit_Arel_Nodes_WithRecursive o
-
"WITH RECURSIVE #{o.children.map { |x| visit x }.join(', ')}"
-
end
-
-
1
def visit_Arel_Nodes_Union o
-
"( #{visit o.left} UNION #{visit o.right} )"
-
end
-
-
1
def visit_Arel_Nodes_UnionAll o
-
"( #{visit o.left} UNION ALL #{visit o.right} )"
-
end
-
-
1
def visit_Arel_Nodes_Intersect o
-
"( #{visit o.left} INTERSECT #{visit o.right} )"
-
end
-
-
1
def visit_Arel_Nodes_Except o
-
"( #{visit o.left} EXCEPT #{visit o.right} )"
-
end
-
-
1
def visit_Arel_Nodes_NamedWindow o
-
"#{quote_column_name o.name} AS #{visit_Arel_Nodes_Window o}"
-
end
-
-
1
def visit_Arel_Nodes_Window o
-
s = [
-
("ORDER BY #{o.orders.map { |x| visit(x) }.join(', ')}" unless o.orders.empty?),
-
(visit o.framing if o.framing)
-
].compact.join ' '
-
"(#{s})"
-
end
-
-
1
def visit_Arel_Nodes_Rows o
-
if o.expr
-
"ROWS #{visit o.expr}"
-
else
-
"ROWS"
-
end
-
end
-
-
1
def visit_Arel_Nodes_Range o
-
if o.expr
-
"RANGE #{visit o.expr}"
-
else
-
"RANGE"
-
end
-
end
-
-
1
def visit_Arel_Nodes_Preceding o
-
"#{o.expr ? visit(o.expr) : 'UNBOUNDED'} PRECEDING"
-
end
-
-
1
def visit_Arel_Nodes_Following o
-
"#{o.expr ? visit(o.expr) : 'UNBOUNDED'} FOLLOWING"
-
end
-
-
1
def visit_Arel_Nodes_CurrentRow o
-
"CURRENT ROW"
-
end
-
-
1
def visit_Arel_Nodes_Over o
-
case o.right
-
when nil
-
"#{visit o.left} OVER ()"
-
when Arel::Nodes::SqlLiteral
-
"#{visit o.left} OVER #{visit o.right}"
-
when String, Symbol
-
"#{visit o.left} OVER #{quote_column_name o.right.to_s}"
-
else
-
"#{visit o.left} OVER #{visit o.right}"
-
end
-
end
-
-
1
def visit_Arel_Nodes_Having o
-
"HAVING #{visit o.expr}"
-
end
-
-
1
def visit_Arel_Nodes_Offset o
-
"OFFSET #{visit o.expr}"
-
end
-
-
1
def visit_Arel_Nodes_Limit o
-
"LIMIT #{visit o.expr}"
-
end
-
-
# FIXME: this does nothing on most databases, but does on MSSQL
-
1
def visit_Arel_Nodes_Top o
-
""
-
end
-
-
1
def visit_Arel_Nodes_Lock o
-
visit o.expr
-
end
-
-
1
def visit_Arel_Nodes_Grouping o
-
"(#{visit o.expr})"
-
end
-
-
1
def visit_Arel_SelectManager o
-
"(#{o.to_sql.rstrip})"
-
end
-
-
1
def visit_Arel_Nodes_Ascending o
-
"#{visit o.expr} ASC"
-
end
-
-
1
def visit_Arel_Nodes_Descending o
-
"#{visit o.expr} DESC"
-
end
-
-
1
def visit_Arel_Nodes_Group o
-
visit o.expr
-
end
-
-
1
def visit_Arel_Nodes_NamedFunction o
-
"#{o.name}(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
visit x
-
}.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}"
-
end
-
-
1
def visit_Arel_Nodes_Extract o
-
"EXTRACT(#{o.field.to_s.upcase} FROM #{visit o.expr})#{o.alias ? " AS #{visit o.alias}" : ''}"
-
end
-
-
1
def visit_Arel_Nodes_Count o
-
"COUNT(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
visit x
-
}.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}"
-
end
-
-
1
def visit_Arel_Nodes_Sum o
-
"SUM(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
visit x }.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}"
-
end
-
-
1
def visit_Arel_Nodes_Max o
-
"MAX(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
visit x }.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}"
-
end
-
-
1
def visit_Arel_Nodes_Min o
-
"MIN(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
visit x }.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}"
-
end
-
-
1
def visit_Arel_Nodes_Avg o
-
"AVG(#{o.distinct ? 'DISTINCT ' : ''}#{o.expressions.map { |x|
-
visit x }.join(', ')})#{o.alias ? " AS #{visit o.alias}" : ''}"
-
end
-
-
1
def visit_Arel_Nodes_TableAlias o
-
"#{visit o.relation} #{quote_table_name o.name}"
-
end
-
-
1
def visit_Arel_Nodes_Between o
-
"#{visit o.left} BETWEEN #{visit o.right}"
-
end
-
-
1
def visit_Arel_Nodes_GreaterThanOrEqual o
-
"#{visit o.left} >= #{visit o.right}"
-
end
-
-
1
def visit_Arel_Nodes_GreaterThan o
-
"#{visit o.left} > #{visit o.right}"
-
end
-
-
1
def visit_Arel_Nodes_LessThanOrEqual o
-
"#{visit o.left} <= #{visit o.right}"
-
end
-
-
1
def visit_Arel_Nodes_LessThan o
-
"#{visit o.left} < #{visit o.right}"
-
end
-
-
1
def visit_Arel_Nodes_Matches o
-
"#{visit o.left} LIKE #{visit o.right}"
-
end
-
-
1
def visit_Arel_Nodes_DoesNotMatch o
-
"#{visit o.left} NOT LIKE #{visit o.right}"
-
end
-
-
1
def visit_Arel_Nodes_JoinSource o
-
[
-
(visit(o.left) if o.left),
-
o.right.map { |j| visit j }.join(' ')
-
].compact.join ' '
-
end
-
-
1
def visit_Arel_Nodes_StringJoin o
-
visit o.left
-
end
-
-
1
def visit_Arel_Nodes_OuterJoin o
-
"LEFT OUTER JOIN #{visit o.left} #{visit o.right}"
-
end
-
-
1
def visit_Arel_Nodes_InnerJoin o
-
s = "INNER JOIN #{visit o.left}"
-
if o.right
-
s << SPACE
-
s << visit(o.right)
-
end
-
s
-
end
-
-
1
def visit_Arel_Nodes_On o
-
"ON #{visit o.expr}"
-
end
-
-
1
def visit_Arel_Nodes_Not o
-
"NOT (#{visit o.expr})"
-
end
-
-
1
def visit_Arel_Table o
-
if o.table_alias
-
"#{quote_table_name o.name} #{quote_table_name o.table_alias}"
-
else
-
quote_table_name o.name
-
end
-
end
-
-
1
def visit_Arel_Nodes_In o
-
if Array === o.right && o.right.empty?
-
'1=0'
-
else
-
"#{visit o.left} IN (#{visit o.right})"
-
end
-
end
-
-
1
def visit_Arel_Nodes_NotIn o
-
if Array === o.right && o.right.empty?
-
'1=1'
-
else
-
"#{visit o.left} NOT IN (#{visit o.right})"
-
end
-
end
-
-
1
def visit_Arel_Nodes_And o
-
o.children.map { |x| visit x }.join ' AND '
-
end
-
-
1
def visit_Arel_Nodes_Or o
-
"#{visit o.left} OR #{visit o.right}"
-
end
-
-
1
def visit_Arel_Nodes_Assignment o
-
right = quote(o.right, column_for(o.left))
-
"#{visit o.left} = #{right}"
-
end
-
-
1
def visit_Arel_Nodes_Equality o
-
right = o.right
-
-
if right.nil?
-
"#{visit o.left} IS NULL"
-
else
-
"#{visit o.left} = #{visit right}"
-
end
-
end
-
-
1
def visit_Arel_Nodes_NotEqual o
-
right = o.right
-
-
if right.nil?
-
"#{visit o.left} IS NOT NULL"
-
else
-
"#{visit o.left} != #{visit right}"
-
end
-
end
-
-
1
def visit_Arel_Nodes_As o
-
"#{visit o.left} AS #{visit o.right}"
-
end
-
-
1
def visit_Arel_Nodes_UnqualifiedColumn o
-
"#{quote_column_name o.name}"
-
end
-
-
1
def visit_Arel_Attributes_Attribute o
-
self.last_column = column_for o
-
join_name = o.relation.table_alias || o.relation.name
-
"#{quote_table_name join_name}.#{quote_column_name o.name}"
-
end
-
1
alias :visit_Arel_Attributes_Integer :visit_Arel_Attributes_Attribute
-
1
alias :visit_Arel_Attributes_Float :visit_Arel_Attributes_Attribute
-
1
alias :visit_Arel_Attributes_Decimal :visit_Arel_Attributes_Attribute
-
1
alias :visit_Arel_Attributes_String :visit_Arel_Attributes_Attribute
-
1
alias :visit_Arel_Attributes_Time :visit_Arel_Attributes_Attribute
-
1
alias :visit_Arel_Attributes_Boolean :visit_Arel_Attributes_Attribute
-
-
1
def literal o; o end
-
-
1
alias :visit_Arel_Nodes_BindParam :literal
-
1
alias :visit_Arel_Nodes_SqlLiteral :literal
-
1
alias :visit_Arel_SqlLiteral :literal # This is deprecated
-
1
alias :visit_Bignum :literal
-
1
alias :visit_Fixnum :literal
-
-
1
def quoted o
-
quote(o, last_column)
-
end
-
-
1
alias :visit_ActiveSupport_Multibyte_Chars :quoted
-
1
alias :visit_ActiveSupport_StringInquirer :quoted
-
1
alias :visit_BigDecimal :quoted
-
1
alias :visit_Class :quoted
-
1
alias :visit_Date :quoted
-
1
alias :visit_DateTime :quoted
-
1
alias :visit_FalseClass :quoted
-
1
alias :visit_Float :quoted
-
1
alias :visit_Hash :quoted
-
1
alias :visit_NilClass :quoted
-
1
alias :visit_String :quoted
-
1
alias :visit_Symbol :quoted
-
1
alias :visit_Time :quoted
-
1
alias :visit_TrueClass :quoted
-
-
1
def visit_Arel_Nodes_InfixOperation o
-
"#{visit o.left} #{o.operator} #{visit o.right}"
-
end
-
-
1
alias :visit_Arel_Nodes_Addition :visit_Arel_Nodes_InfixOperation
-
1
alias :visit_Arel_Nodes_Subtraction :visit_Arel_Nodes_InfixOperation
-
1
alias :visit_Arel_Nodes_Multiplication :visit_Arel_Nodes_InfixOperation
-
1
alias :visit_Arel_Nodes_Division :visit_Arel_Nodes_InfixOperation
-
-
1
def visit_Array o
-
o.map { |x| visit x }.join(', ')
-
end
-
-
1
def quote value, column = nil
-
@connection.quote value, column
-
end
-
-
1
def quote_table_name name
-
return name if Arel::Nodes::SqlLiteral === name
-
@quoted_tables[name] ||= @connection.quote_table_name(name)
-
end
-
-
1
def quote_column_name name
-
@quoted_columns[name] ||= Arel::Nodes::SqlLiteral === name ? name : @connection.quote_column_name(name)
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class Visitor
-
1
def accept object
-
visit object
-
end
-
-
1
private
-
-
1
DISPATCH = Hash.new do |hash, klass|
-
hash[klass] = "visit_#{(klass.name || '').gsub('::', '_')}"
-
end
-
-
1
def dispatch
-
DISPATCH
-
end
-
-
1
def visit object
-
send dispatch[object.class], object
-
rescue NoMethodError => e
-
raise e if respond_to?(dispatch[object.class], true)
-
superklass = object.class.ancestors.find { |klass|
-
respond_to?(dispatch[klass], true)
-
}
-
raise(TypeError, "Cannot visit #{object.class}") unless superklass
-
dispatch[object.class] = dispatch[superklass]
-
retry
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module Visitors
-
1
class WhereSql < Arel::Visitors::ToSql
-
1
def visit_Arel_Nodes_SelectCore o
-
"WHERE #{o.wheres.map { |x| visit x }.join ' AND ' }"
-
end
-
end
-
end
-
end
-
1
module Arel
-
1
module WindowPredications
-
-
1
def over(expr = nil)
-
Nodes::Over.new(self, expr)
-
end
-
-
end
-
end
-
1
require 'mocha/class_method'
-
-
1
module Mocha
-
-
1
class AnyInstanceMethod < ClassMethod
-
-
1
def mock
-
stubbee.any_instance.mocha
-
end
-
-
1
def reset_mocha
-
stubbee.any_instance.reset_mocha
-
end
-
-
1
def hide_original_method
-
if method_exists?(method)
-
begin
-
@original_method = stubbee.instance_method(method)
-
if @original_method && @original_method.owner == stubbee
-
@original_visibility = :public
-
if stubbee.protected_instance_methods.include?(method)
-
@original_visibility = :protected
-
elsif stubbee.private_instance_methods.include?(method)
-
@original_visibility = :private
-
end
-
stubbee.send(:remove_method, method)
-
end
-
rescue NameError
-
# deal with nasties like ActiveRecord::Associations::AssociationProxy
-
end
-
end
-
end
-
-
1
def define_new_method
-
stubbee.class_eval(%{
-
def #{method}(*args, &block)
-
self.class.any_instance.mocha.method_missing(:#{method}, *args, &block)
-
end
-
}, __FILE__, __LINE__)
-
end
-
-
1
def remove_new_method
-
stubbee.send(:remove_method, method)
-
end
-
-
1
def restore_original_method
-
if @original_method && @original_method.owner == stubbee
-
stubbee.send(:define_method, method, @original_method)
-
stubbee.send(@original_visibility, method)
-
end
-
end
-
-
1
def method_exists?(method)
-
return true if stubbee.public_instance_methods(false).include?(method)
-
return true if stubbee.protected_instance_methods(false).include?(method)
-
return true if stubbee.private_instance_methods(false).include?(method)
-
return false
-
end
-
-
end
-
-
end
-
1
require 'mocha/parameter_matchers'
-
1
require 'mocha/hooks'
-
1
require 'mocha/mockery'
-
1
require 'mocha/sequence'
-
1
require 'mocha/object_methods'
-
1
require 'mocha/module_methods'
-
1
require 'mocha/class_methods'
-
-
1
module Mocha
-
-
# Methods added to +Test::Unit::TestCase+, +MiniTest::Unit::TestCase+ or equivalent.
-
1
module API
-
-
1
include ParameterMatchers
-
1
include Hooks
-
-
# @private
-
1
def self.included(mod)
-
1
Object.send(:include, Mocha::ObjectMethods)
-
1
Module.send(:include, Mocha::ModuleMethods)
-
1
Class.send(:include, Mocha::ClassMethods)
-
end
-
-
# Builds a new mock object
-
#
-
# @param [String] name identifies mock object in error messages.
-
# @param [Hash] expected_methods_vs_return_values expected method name symbols as keys and corresponding return values as values - these expectations are setup as if {Mock#expects} were called multiple times.
-
# @yield optional block to be evaluated against the mock object instance, giving an alternative way to setup expectations.
-
# @return [Mock] a new mock object
-
#
-
# @overload def mock(name, &block)
-
# @overload def mock(expected_methods_vs_return_values = {}, &block)
-
# @overload def mock(name, expected_methods_vs_return_values = {}, &block)
-
#
-
# @example Using expected_methods_vs_return_values Hash to setup expectations.
-
# def test_motor_starts_and_stops
-
# motor = mock('motor', :start => true, :stop => true)
-
# assert motor.start
-
# assert motor.stop
-
# # an error will be raised unless both Motor#start and Motor#stop have been called
-
# end
-
# @example Using the optional block to setup expectations & stubbed methods.
-
# def test_motor_starts_and_stops
-
# motor = mock('motor') do
-
# expects(:start).with(100.rpm).returns(true)
-
# stubs(:stop).returns(true)
-
# end
-
# assert motor.start(100.rpm)
-
# assert motor.stop
-
# # an error will only be raised if Motor#start(100.rpm) has not been called
-
# end
-
1
def mock(*arguments, &block)
-
1
name = arguments.shift if arguments.first.is_a?(String)
-
1
expectations = arguments.shift || {}
-
1
mock = name ? Mockery.instance.named_mock(name, &block) : Mockery.instance.unnamed_mock(&block)
-
1
mock.expects(expectations)
-
1
mock
-
end
-
-
# Builds a new mock object
-
#
-
# @param [String] name identifies mock object in error messages.
-
# @param [Hash] stubbed_methods_vs_return_values stubbed method name symbols as keys and corresponding return values as values - these stubbed methods are setup as if {Mock#stubs} were called multiple times.
-
# @yield optional block to be evaluated against the mock object instance, giving an alternative way to setup stubbed methods.
-
# @return [Mock] a new mock object
-
#
-
# @overload def stub(name, &block)
-
# @overload def stub(stubbed_methods_vs_return_values = {}, &block)
-
# @overload def stub(name, stubbed_methods_vs_return_values = {}, &block)
-
#
-
# @example Using stubbed_methods_vs_return_values Hash to setup stubbed methods.
-
# def test_motor_starts_and_stops
-
# motor = mock('motor', :start => true, :stop => true)
-
# assert motor.start
-
# assert motor.stop
-
# # an error will not be raised even if either Motor#start or Motor#stop has not been called
-
# end
-
#
-
# @example Using the optional block to setup expectations & stubbed methods.
-
# def test_motor_starts_and_stops
-
# motor = mock('motor') do
-
# expects(:start).with(100.rpm).returns(true)
-
# stubs(:stop).returns(true)
-
# end
-
# assert motor.start(100.rpm)
-
# assert motor.stop
-
# # an error will only be raised if Motor#start(100.rpm) has not been called
-
# end
-
1
def stub(*arguments, &block)
-
name = arguments.shift if arguments.first.is_a?(String)
-
expectations = arguments.shift || {}
-
stub = name ? Mockery.instance.named_mock(name, &block) : Mockery.instance.unnamed_mock(&block)
-
stub.stubs(expectations)
-
stub
-
end
-
-
# Builds a mock object that accepts calls to any method. By default it will return +nil+ for any method call.
-
#
-
# @param [String] name identifies mock object in error messages.
-
# @param [Hash] stubbed_methods_vs_return_values stubbed method name symbols as keys and corresponding return values as values - these stubbed methods are setup as if {Mock#stubs} were called multiple times.
-
# @yield optional block to be evaluated against the mock object instance, giving an alternative way to setup stubbed methods.
-
# @return [Mock] a new mock object
-
#
-
# @overload def stub_everything(name, &block)
-
# @overload def stub_everything(stubbed_methods_vs_return_values = {}, &block)
-
# @overload def stub_everything(name, stubbed_methods_vs_return_values = {}, &block)
-
#
-
# @example Ignore invocations of irrelevant methods.
-
# def test_motor_stops
-
# motor = stub_everything('motor', :stop => true)
-
# assert_nil motor.irrelevant_method_1 # => no error raised
-
# assert_nil motor.irrelevant_method_2 # => no error raised
-
# assert motor.stop
-
# end
-
1
def stub_everything(*arguments, &block)
-
name = arguments.shift if arguments.first.is_a?(String)
-
expectations = arguments.shift || {}
-
stub = name ? Mockery.instance.named_mock(name, &block) : Mockery.instance.unnamed_mock(&block)
-
stub.stub_everything
-
stub.stubs(expectations)
-
stub
-
end
-
-
# Builds a new sequence which can be used to constrain the order in which expectations can occur.
-
#
-
# Specify that an expected invocation must occur within a named {Sequence} by using {Expectation#in_sequence}.
-
#
-
# @return [Sequence] a new sequence
-
#
-
# @see Expectation#in_sequence
-
#
-
# @example Ensure methods on egg are invoked in correct order.
-
# breakfast = sequence('breakfast')
-
#
-
# egg = mock('egg') do
-
# expects(:crack).in_sequence(breakfast)
-
# expects(:fry).in_sequence(breakfast)
-
# expects(:eat).in_sequence(breakfast)
-
# end
-
1
def sequence(name)
-
Sequence.new(name)
-
end
-
-
# Builds a new state machine which can be used to constrain the order in which expectations can occur.
-
#
-
# Specify the initial state of the state machine by using {StateMachine#starts_as}.
-
#
-
# Specify that an expected invocation should change the state of the state machine by using {Expectation#then}.
-
#
-
# Specify that an expected invocation should be constrained to occur within a particular +state+ by using {Expectation#when}.
-
#
-
# A test can contain multiple state machines.
-
#
-
# @return [StateMachine] a new state machine
-
#
-
# @see Expectation#then
-
# @see Expectation#when
-
# @see StateMachine
-
# @example Constrain expected invocations to occur in particular states.
-
# power = states('power').starts_as('off')
-
#
-
# radio = mock('radio') do
-
# expects(:switch_on).then(power.is('on'))
-
# expects(:select_channel).with('BBC Radio 4').when(power.is('on'))
-
# expects(:adjust_volume).with(+5).when(power.is('on'))
-
# expects(:select_channel).with('BBC World Service').when(power.is('on'))
-
# expects(:adjust_volume).with(-5).when(power.is('on'))
-
# expects(:switch_off).then(power.is('off'))
-
# end
-
1
def states(name)
-
Mockery.instance.new_state_machine(name)
-
end
-
-
end
-
-
end
-
1
module Mocha
-
-
1
class ArgumentIterator
-
-
1
def initialize(argument)
-
196
@argument = argument
-
end
-
-
1
def each(&block)
-
196
if @argument.is_a?(Hash) then
-
1
@argument.each do |method_name, return_value|
-
block.call(method_name, return_value)
-
end
-
else
-
195
block.call(@argument)
-
end
-
end
-
-
end
-
-
end
-
1
module Mocha
-
-
1
class BacktraceFilter
-
-
1
LIB_DIRECTORY = File.expand_path(File.join(File.dirname(__FILE__), "..")) + File::SEPARATOR
-
-
1
def initialize(lib_directory = LIB_DIRECTORY)
-
@path_pattern = Regexp.new(lib_directory)
-
end
-
-
1
def filtered(backtrace)
-
backtrace.reject { |location| @path_pattern.match(File.expand_path(location)) }
-
end
-
-
end
-
-
end
-
1
module Mocha
-
-
1
class Cardinality
-
-
1
INFINITY = 1 / 0.0
-
-
1
class << self
-
-
1
def exactly(count)
-
113
new(count, count)
-
end
-
-
1
def at_least(count)
-
66
new(count, INFINITY)
-
end
-
-
1
def at_most(count)
-
new(0, count)
-
end
-
-
1
def times(range_or_count)
-
case range_or_count
-
when Range then new(range_or_count.first, range_or_count.last)
-
else new(range_or_count, range_or_count)
-
end
-
end
-
-
end
-
-
1
def initialize(required, maximum)
-
179
@required, @maximum = required, maximum
-
end
-
-
1
def invocations_allowed?(invocation_count)
-
283
invocation_count < maximum
-
end
-
-
1
def satisfied?(invocations_so_far)
-
invocations_so_far >= required
-
end
-
-
1
def needs_verifying?
-
!allowed_any_number_of_times?
-
end
-
-
1
def verified?(invocation_count)
-
98
(invocation_count >= required) && (invocation_count <= maximum)
-
end
-
-
1
def allowed_any_number_of_times?
-
required == 0 && infinite?(maximum)
-
end
-
-
1
def used?(invocation_count)
-
(invocation_count > 0) || (maximum == 0)
-
end
-
-
1
def mocha_inspect
-
if allowed_any_number_of_times?
-
"allowed any number of times"
-
else
-
if required == 0 && maximum == 0
-
"expected never"
-
elsif required == maximum
-
"expected exactly #{times(required)}"
-
elsif infinite?(maximum)
-
"expected at least #{times(required)}"
-
elsif required == 0
-
"expected at most #{times(maximum)}"
-
else
-
"expected between #{required} and #{times(maximum)}"
-
end
-
end
-
end
-
-
1
protected
-
-
1
attr_reader :required, :maximum
-
-
1
def times(number)
-
case number
-
when 0 then "no times"
-
when 1 then "once"
-
when 2 then "twice"
-
else "#{number} times"
-
end
-
end
-
-
1
def infinite?(number)
-
number.respond_to?(:infinite?) && number.infinite?
-
end
-
-
end
-
-
end
-
1
module Mocha
-
-
1
class Central
-
-
1
attr_accessor :stubba_methods
-
-
1
def initialize
-
2856
self.stubba_methods = []
-
end
-
-
1
def stub(method)
-
114
unless stubba_methods.detect { |m| m.matches?(method) }
-
85
method.stub
-
85
stubba_methods.push(method)
-
end
-
end
-
-
1
def unstub(method)
-
170
if existing = stubba_methods.detect { |m| m.matches?(method) }
-
85
existing.unstub
-
85
stubba_methods.delete(existing)
-
end
-
end
-
-
1
def unstub_all
-
2856
while stubba_methods.any? do
-
85
unstub(stubba_methods.first)
-
end
-
end
-
-
end
-
-
end
-
1
module Mocha
-
-
1
class ChangeStateSideEffect
-
-
1
def initialize(state)
-
@state = state
-
end
-
-
1
def perform
-
@state.activate
-
end
-
-
1
def mocha_inspect
-
"then #{@state.mocha_inspect}"
-
end
-
-
end
-
-
end
-
1
require 'metaclass'
-
-
1
module Mocha
-
-
1
class ClassMethod
-
-
1
attr_reader :stubbee, :method
-
-
1
def initialize(stubbee, method)
-
97
@stubbee, @original_method = stubbee, nil
-
97
@method = RUBY_VERSION < '1.9' ? method.to_s : method.to_sym
-
end
-
-
1
def stub
-
85
hide_original_method
-
85
define_new_method
-
end
-
-
1
def unstub
-
85
remove_new_method
-
85
restore_original_method
-
85
mock.unstub(method.to_sym)
-
85
unless mock.any_expectations?
-
82
reset_mocha
-
end
-
end
-
-
1
def mock
-
170
stubbee.mocha
-
end
-
-
1
def reset_mocha
-
82
stubbee.reset_mocha
-
end
-
-
1
def hide_original_method
-
85
if method_exists?(method)
-
68
begin
-
68
@original_method = stubbee._method(method)
-
68
if @original_method && @original_method.owner == stubbee.__metaclass__
-
52
@original_visibility = :public
-
52
if stubbee.__metaclass__.protected_instance_methods.include?(method)
-
@original_visibility = :protected
-
elsif stubbee.__metaclass__.private_instance_methods.include?(method)
-
@original_visibility = :private
-
end
-
52
stubbee.__metaclass__.send(:remove_method, method)
-
end
-
rescue NameError
-
# deal with nasties like ActiveRecord::Associations::AssociationProxy
-
end
-
end
-
end
-
-
1
def define_new_method
-
85
stubbee.__metaclass__.class_eval(%{
-
def #{method}(*args, &block)
-
mocha.method_missing(:#{method}, *args, &block)
-
end
-
}, __FILE__, __LINE__)
-
end
-
-
1
def remove_new_method
-
85
stubbee.__metaclass__.send(:remove_method, method)
-
end
-
-
1
def restore_original_method
-
85
if @original_method && @original_method.owner == stubbee.__metaclass__
-
52
if RUBY_VERSION < '1.9'
-
original_method = @original_method
-
stubbee.__metaclass__.send(:define_method, method) do |*args, &block|
-
original_method.call(*args, &block)
-
end
-
else
-
52
stubbee.__metaclass__.send(:define_method, method, @original_method)
-
end
-
52
stubbee.__metaclass__.send(@original_visibility, method)
-
end
-
end
-
-
1
def matches?(other)
-
102
return false unless (other.class == self.class)
-
100
(stubbee.object_id == other.stubbee.object_id) and (method == other.method)
-
end
-
-
1
alias_method :==, :eql?
-
-
1
def to_s
-
"#{stubbee}.#{method}"
-
end
-
-
1
def method_exists?(method)
-
58
symbol = method.to_sym
-
58
__metaclass__ = stubbee.__metaclass__
-
58
__metaclass__.public_method_defined?(symbol) || __metaclass__.protected_method_defined?(symbol) || __metaclass__.private_method_defined?(symbol)
-
end
-
-
end
-
-
end
-
1
require 'mocha/mockery'
-
1
require 'mocha/class_method'
-
1
require 'mocha/any_instance_method'
-
-
1
module Mocha
-
-
# Methods added to all classes to allow mocking and stubbing on real (i.e. non-mock) objects.
-
1
module ClassMethods
-
-
# @private
-
1
def stubba_method
-
70
Mocha::ClassMethod
-
end
-
-
# @private
-
1
class AnyInstance
-
-
1
def initialize(klass)
-
@stubba_object = klass
-
end
-
-
1
def mocha
-
@mocha ||= Mocha::Mockery.instance.mock_impersonating_any_instance_of(@stubba_object)
-
end
-
-
1
def stubba_method
-
Mocha::AnyInstanceMethod
-
end
-
-
1
def stubba_object
-
@stubba_object
-
end
-
-
1
def method_exists?(method, include_public_methods = true)
-
if include_public_methods
-
return true if @stubba_object.public_instance_methods(include_superclass_methods = true).include?(method)
-
end
-
return true if @stubba_object.protected_instance_methods(include_superclass_methods = true).include?(method)
-
return true if @stubba_object.private_instance_methods(include_superclass_methods = true).include?(method)
-
return false
-
end
-
-
end
-
-
# @return [Mock] a mock object which will detect calls to any instance of this class.
-
# @raise [StubbingError] if attempting to stub method which is not allowed.
-
#
-
# @example Return false to invocation of +Product#save+ for any instance of +Product+.
-
# Product.any_instance.stubs(:save).returns(false)
-
# product_1 = Product.new
-
# assert_equal false, product_1.save
-
# product_2 = Product.new
-
# assert_equal false, product_2.save
-
1
def any_instance
-
if frozen?
-
raise StubbingError.new("can't stub method on frozen object: #{mocha_inspect}.any_instance", caller)
-
end
-
@any_instance ||= AnyInstance.new(self)
-
end
-
-
end
-
-
end
-
1
module Mocha
-
-
# Configuration settings.
-
1
class Configuration
-
-
1
DEFAULTS = {
-
:stubbing_method_unnecessarily => :allow,
-
:stubbing_method_on_non_mock_object => :allow,
-
:stubbing_non_existent_method => :allow,
-
:stubbing_non_public_method => :allow,
-
:stubbing_method_on_nil => :prevent,
-
}
-
-
1
class << self
-
-
# Allow the specified +action+.
-
#
-
# @param [Symbol] action one of +:stubbing_method_unnecessarily+, +:stubbing_method_on_non_mock_object+, +:stubbing_non_existent_method+, +:stubbing_non_public_method+, +:stubbing_method_on_nil+.
-
# @yield optional block during which the configuration change will be changed before being returned to its original value at the end of the block.
-
1
def allow(action, &block)
-
change_config action, :allow, &block
-
end
-
-
# @private
-
1
def allow?(action)
-
486
configuration[action] == :allow
-
end
-
-
# Warn if the specified +action+ is attempted.
-
#
-
# @param [Symbol] action one of +:stubbing_method_unnecessarily+, +:stubbing_method_on_non_mock_object+, +:stubbing_non_existent_method+, +:stubbing_non_public_method+, +:stubbing_method_on_nil+.
-
# @yield optional block during which the configuration change will be changed before being returned to its original value at the end of the block.
-
1
def warn_when(action, &block)
-
change_config action, :warn, &block
-
end
-
-
# @private
-
1
def warn_when?(action)
-
configuration[action] == :warn
-
end
-
-
# Raise a {StubbingError} if if the specified +action+ is attempted.
-
#
-
# @param [Symbol] action one of +:stubbing_method_unnecessarily+, +:stubbing_method_on_non_mock_object+, +:stubbing_non_existent_method+, +:stubbing_non_public_method+, +:stubbing_method_on_nil+.
-
# @yield optional block during which the configuration change will be changed before being returned to its original value at the end of the block.
-
1
def prevent(action, &block)
-
change_config action, :prevent, &block
-
end
-
-
# @private
-
1
def prevent?(action)
-
configuration[action] == :prevent
-
end
-
-
# @private
-
1
def reset_configuration
-
@configuration = nil
-
end
-
-
1
private
-
-
# @private
-
1
def configuration
-
486
@configuration ||= DEFAULTS.dup
-
end
-
-
# @private
-
1
def change_config(action, new_value, &block)
-
if block_given?
-
temporarily_change_config action, new_value, &block
-
else
-
configuration[action] = new_value
-
end
-
end
-
-
# @private
-
1
def temporarily_change_config(action, new_value, &block)
-
original_value = configuration[action]
-
configuration[action] = new_value
-
yield
-
ensure
-
configuration[action] = original_value
-
end
-
-
end
-
-
end
-
-
end
-
1
module Mocha
-
-
1
class ExceptionRaiser
-
-
1
def initialize(exception, message)
-
1
@exception, @message = exception, message
-
end
-
-
1
def evaluate
-
1
raise @exception, @exception.to_s if @exception.is_a?(Module) && (@exception < Interrupt)
-
1
raise @exception, @message if @message
-
raise @exception
-
end
-
-
end
-
-
end
-
1
require 'mocha/method_matcher'
-
1
require 'mocha/parameters_matcher'
-
1
require 'mocha/expectation_error'
-
1
require 'mocha/return_values'
-
1
require 'mocha/exception_raiser'
-
1
require 'mocha/thrower'
-
1
require 'mocha/yield_parameters'
-
1
require 'mocha/is_a'
-
1
require 'mocha/in_state_ordering_constraint'
-
1
require 'mocha/change_state_side_effect'
-
1
require 'mocha/cardinality'
-
-
1
module Mocha
-
-
# Methods on expectations returned from {Mock#expects}, {Mock#stubs}, {ObjectMethods#expects} and {ObjectMethods#stubs}.
-
1
class Expectation
-
-
# Modifies expectation so that the number of calls to the expected method must be within a specific +range+.
-
#
-
# @param [Range,Integer] range specifies the allowable range in the number of expected invocations.
-
# @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained.
-
#
-
# @example Specifying a specific number of expected invocations.
-
# object = mock()
-
# object.expects(:expected_method).times(3)
-
# 3.times { object.expected_method }
-
# # => verify succeeds
-
#
-
# object = mock()
-
# object.expects(:expected_method).times(3)
-
# 2.times { object.expected_method }
-
# # => verify fails
-
#
-
# @example Specifying a range in the number of expected invocations.
-
# object = mock()
-
# object.expects(:expected_method).times(2..4)
-
# 3.times { object.expected_method }
-
# # => verify succeeds
-
#
-
# object = mock()
-
# object.expects(:expected_method).times(2..4)
-
# object.expected_method
-
# # => verify fails
-
1
def times(range)
-
@cardinality = Cardinality.times(range)
-
self
-
end
-
-
# Modifies expectation so that the expected method must be called exactly twice.
-
#
-
# @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained.
-
#
-
# @example Expected method must be invoked exactly twice.
-
# object = mock()
-
# object.expects(:expected_method).twice
-
# object.expected_method
-
# object.expected_method
-
# # => verify succeeds
-
#
-
# object = mock()
-
# object.expects(:expected_method).twice
-
# object.expected_method
-
# object.expected_method
-
# object.expected_method # => unexpected invocation
-
#
-
# object = mock()
-
# object.expects(:expected_method).twice
-
# object.expected_method
-
# # => verify fails
-
1
def twice
-
@cardinality = Cardinality.exactly(2)
-
self
-
end
-
-
# Modifies expectation so that the expected method must be called exactly once.
-
#
-
# Note that this is the default behaviour for an expectation, but you may wish to use it for clarity/emphasis.
-
#
-
# @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained.
-
#
-
# @example Expected method must be invoked exactly once.
-
# object = mock()
-
# object.expects(:expected_method).once
-
# object.expected_method
-
# # => verify succeeds
-
#
-
# object = mock()
-
# object.expects(:expected_method).once
-
# object.expected_method
-
# object.expected_method # => unexpected invocation
-
#
-
# object = mock()
-
# object.expects(:expected_method).once
-
# # => verify fails
-
1
def once
-
1
@cardinality = Cardinality.exactly(1)
-
1
self
-
end
-
-
# Modifies expectation so that the expected method must never be called.
-
#
-
# @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained.
-
#
-
# @example Expected method must never be called.
-
# object = mock()
-
# object.expects(:expected_method).never
-
# object.expected_method # => unexpected invocation
-
#
-
# object = mock()
-
# object.expects(:expected_method).never
-
# # => verify succeeds
-
1
def never
-
14
@cardinality = Cardinality.exactly(0)
-
14
self
-
end
-
-
# Modifies expectation so that the expected method must be called at least a +minimum_number_of_times+.
-
#
-
# @param [Integer] minimum_number_of_times minimum number of expected invocations.
-
# @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained.
-
#
-
# @example Expected method must be called at least twice.
-
# object = mock()
-
# object.expects(:expected_method).at_least(2)
-
# 3.times { object.expected_method }
-
# # => verify succeeds
-
#
-
# object = mock()
-
# object.expects(:expected_method).at_least(2)
-
# object.expected_method
-
# # => verify fails
-
1
def at_least(minimum_number_of_times)
-
66
@cardinality = Cardinality.at_least(minimum_number_of_times)
-
66
self
-
end
-
-
# Modifies expectation so that the expected method must be called at least once.
-
#
-
# @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained.
-
#
-
# @example Expected method must be called at least once.
-
# object = mock()
-
# object.expects(:expected_method).at_least_once
-
# object.expected_method
-
# # => verify succeeds
-
#
-
# object = mock()
-
# object.expects(:expected_method).at_least_once
-
# # => verify fails
-
1
def at_least_once
-
at_least(1)
-
self
-
end
-
-
# Modifies expectation so that the expected method must be called at most a +maximum_number_of_times+.
-
#
-
# @param [Integer] maximum_number_of_times maximum number of expected invocations.
-
# @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained.
-
#
-
# @example Expected method must be called at most twice.
-
# object = mock()
-
# object.expects(:expected_method).at_most(2)
-
# 2.times { object.expected_method }
-
# # => verify succeeds
-
#
-
# object = mock()
-
# object.expects(:expected_method).at_most(2)
-
# 3.times { object.expected_method } # => unexpected invocation
-
1
def at_most(maximum_number_of_times)
-
@cardinality = Cardinality.at_most(maximum_number_of_times)
-
self
-
end
-
-
# Modifies expectation so that the expected method must be called at most once.
-
#
-
# @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained.
-
#
-
# @example Expected method must be called at most once.
-
# object = mock()
-
# object.expects(:expected_method).at_most_once
-
# object.expected_method
-
# # => verify succeeds
-
#
-
# object = mock()
-
# object.expects(:expected_method).at_most_once
-
# 2.times { object.expected_method } # => unexpected invocation
-
1
def at_most_once()
-
at_most(1)
-
self
-
end
-
-
# Modifies expectation so that the expected method must be called with +expected_parameters+.
-
#
-
# May be used with parameter matchers in {ParameterMatchers}.
-
#
-
# @param [*Array] expected_parameters parameters expected.
-
# @yield optional block specifying custom matching.
-
# @yieldparam [*Array] actual_parameters parameters with which expected method was invoked.
-
# @yieldreturn [Boolean] +true+ if +actual_parameters+ are acceptable.
-
# @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained.
-
#
-
# @example Expected method must be called with expected parameters.
-
# object = mock()
-
# object.expects(:expected_method).with(:param1, :param2)
-
# object.expected_method(:param1, :param2)
-
# # => verify succeeds
-
#
-
# object = mock()
-
# object.expects(:expected_method).with(:param1, :param2)
-
# object.expected_method(:param3)
-
# # => verify fails
-
#
-
# @example Expected method must be called with a value divisible by 4.
-
# object = mock()
-
# object.expects(:expected_method).with() { |value| value % 4 == 0 }
-
# object.expected_method(16)
-
# # => verify succeeds
-
#
-
# object = mock()
-
# object.expects(:expected_method).with() { |value| value % 4 == 0 }
-
# object.expected_method(17)
-
# # => verify fails
-
1
def with(*expected_parameters, &matching_block)
-
11
@parameters_matcher = ParametersMatcher.new(expected_parameters, &matching_block)
-
11
self
-
end
-
-
# Modifies expectation so that when the expected method is called, it yields with the specified +parameters+.
-
#
-
# May be called multiple times on the same expectation for consecutive invocations.
-
#
-
# @param [*Array] parameters parameters to be yielded.
-
# @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained.
-
# @see #then
-
#
-
# @example Yield parameters when expected method is invoked.
-
# object = mock()
-
# object.expects(:expected_method).yields('result')
-
# yielded_value = nil
-
# object.expected_method { |value| yielded_value = value }
-
# yielded_value # => 'result'
-
#
-
# @example Yield different parameters on different invocations of the expected method.
-
# object = mock()
-
# object.stubs(:expected_method).yields(1).then.yields(2)
-
# yielded_values_from_first_invocation = []
-
# yielded_values_from_second_invocation = []
-
# object.expected_method { |value| yielded_values_from_first_invocation << value } # first invocation
-
# object.expected_method { |value| yielded_values_from_second_invocation << value } # second invocation
-
# yielded_values_from_first_invocation # => [1]
-
# yielded_values_from_second_invocation # => [2]
-
1
def yields(*parameters)
-
@yield_parameters.add(*parameters)
-
self
-
end
-
-
# Modifies expectation so that when the expected method is called, it yields multiple times per invocation with the specified +parameter_groups+.
-
#
-
# @param [*Array<Array>] parameter_groups each element of +parameter_groups+ should iself be an +Array+ representing the parameters to be passed to the block for a single yield.
-
# @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained.
-
# @see #then
-
#
-
# @example When the +expected_method+ is called, the stub will invoke the block twice, the first time it passes +'result_1'+, +'result_2'+ as the parameters, and the second time it passes 'result_3' as the parameters.
-
# object = mock()
-
# object.expects(:expected_method).multiple_yields(['result_1', 'result_2'], ['result_3'])
-
# yielded_values = []
-
# object.expected_method { |*values| yielded_values << values }
-
# yielded_values # => [['result_1', 'result_2'], ['result_3]]
-
#
-
# @example Yield different groups of parameters on different invocations of the expected method.
-
# object = mock()
-
# object.stubs(:expected_method).multiple_yields([1, 2], [3]).then.multiple_yields([4], [5, 6])
-
# yielded_values_from_first_invocation = []
-
# yielded_values_from_second_invocation = []
-
# object.expected_method { |*values| yielded_values_from_first_invocation << values } # first invocation
-
# object.expected_method { |*values| yielded_values_from_second_invocation << values } # second invocation
-
# yielded_values_from_first_invocation # => [[1, 2], [3]]
-
# yielded_values_from_second_invocation # => [[4], [5, 6]]
-
1
def multiple_yields(*parameter_groups)
-
@yield_parameters.multiple_add(*parameter_groups)
-
self
-
end
-
-
# Modifies expectation so that when the expected method is called, it returns the specified +value+.
-
#
-
# @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained.
-
# @see #then
-
#
-
# @overload def returns(value)
-
# @param [Object] value value to return on invocation of expected method.
-
# @overload def returns(*values)
-
# @param [*Array] values values to return on consecutive invocations of expected method.
-
#
-
# @example Return the same value on every invocation.
-
# object = mock()
-
# object.stubs(:stubbed_method).returns('result')
-
# object.stubbed_method # => 'result'
-
# object.stubbed_method # => 'result'
-
#
-
# @example Return a different value on consecutive invocations.
-
# object = mock()
-
# object.stubs(:stubbed_method).returns(1, 2)
-
# object.stubbed_method # => 1
-
# object.stubbed_method # => 2
-
#
-
# @example Alternative way to return a different value on consecutive invocations.
-
# object = mock()
-
# object.stubs(:expected_method).returns(1, 2).then.returns(3)
-
# object.expected_method # => 1
-
# object.expected_method # => 2
-
# object.expected_method # => 3
-
#
-
# @example May be called in conjunction with {#raises} on the same expectation.
-
# object = mock()
-
# object.stubs(:expected_method).returns(1, 2).then.raises(Exception)
-
# object.expected_method # => 1
-
# object.expected_method # => 2
-
# object.expected_method # => raises exception of class Exception1
-
#
-
# @example Note that in Ruby a method returning multiple values is exactly equivalent to a method returning an +Array+ of those values.
-
# object = mock()
-
# object.stubs(:expected_method).returns([1, 2])
-
# x, y = object.expected_method
-
# x # => 1
-
# y # => 2
-
1
def returns(*values)
-
67
@return_values += ReturnValues.build(*values)
-
67
self
-
end
-
-
# Modifies expectation so that when the expected method is called, it raises the specified +exception+ with the specified +message+ i.e. calls +Kernel#raise(exception, message)+.
-
#
-
# @param [Class,Exception,String,#exception] exception exception to be raised or message to be passed to RuntimeError.
-
# @param [String] message exception message.
-
# @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained.
-
#
-
# @see Kernel#raise
-
# @see #then
-
#
-
# @overload def raises
-
# @overload def raises(exception)
-
# @overload def raises(exception, message)
-
#
-
# @example Raise specified exception if expected method is invoked.
-
# object = stub()
-
# object.stubs(:expected_method).raises(Exception, 'message')
-
# object.expected_method # => raises exception of class Exception and with message 'message'
-
#
-
# @example Raise custom exception with extra constructor parameters by passing in an instance of the exception.
-
# object = stub()
-
# object.stubs(:expected_method).raises(MyException.new('message', 1, 2, 3))
-
# object.expected_method # => raises the specified instance of MyException
-
#
-
# @example Raise different exceptions on consecutive invocations of the expected method.
-
# object = stub()
-
# object.stubs(:expected_method).raises(Exception1).then.raises(Exception2)
-
# object.expected_method # => raises exception of class Exception1
-
# object.expected_method # => raises exception of class Exception2
-
#
-
# @example Raise an exception on first invocation of expected method and then return values on subsequent invocations.
-
# object = stub()
-
# object.stubs(:expected_method).raises(Exception).then.returns(2, 3)
-
# object.expected_method # => raises exception of class Exception1
-
# object.expected_method # => 2
-
# object.expected_method # => 3
-
1
def raises(exception = RuntimeError, message = nil)
-
1
@return_values += ReturnValues.new(ExceptionRaiser.new(exception, message))
-
1
self
-
end
-
-
# Modifies expectation so that when the expected method is called, it throws the specified +tag+ with the specific return value +object+ i.e. calls +Kernel#throw(tag, object)+.
-
#
-
# @param [Symbol,String] tag tag to throw to transfer control to the active catch block.
-
# @param [Object] object return value for the catch block.
-
# @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained.
-
#
-
# @see Kernel#throw
-
# @see #then
-
#
-
# @overload def throw(tag)
-
# @overload def throw(tag, object)
-
#
-
# @example Throw tag when expected method is invoked.
-
# object = stub()
-
# object.stubs(:expected_method).throws(:done)
-
# object.expected_method # => throws tag :done
-
#
-
# @example Throw tag with return value +object+ c.f. +Kernel#throw+.
-
# object = stub()
-
# object.stubs(:expected_method).throws(:done, 'result')
-
# object.expected_method # => throws tag :done and causes catch block to return 'result'
-
#
-
# @example Throw different tags on consecutive invocations of the expected method.
-
# object = stub()
-
# object.stubs(:expected_method).throws(:done).then.throws(:continue)
-
# object.expected_method # => throws :done
-
# object.expected_method # => throws :continue
-
#
-
# @example Throw tag on first invocation of expected method and then return values for subsequent invocations.
-
# object = stub()
-
# object.stubs(:expected_method).throws(:done).then.returns(2, 3)
-
# object.expected_method # => throws :done
-
# object.expected_method # => 2
-
# object.expected_method # => 3
-
1
def throws(tag, object = nil)
-
@return_values += ReturnValues.new(Thrower.new(tag, object))
-
self
-
end
-
-
# @overload def then
-
# Used as syntactic sugar to improve readability. It has no effect on state of the expectation.
-
# @overload def then(state_machine.is(state_name))
-
# Used to change the +state_machine+ to the state specified by +state_name+ when the expected invocation occurs.
-
# @param [StateMachine::State] state_machine.is(state_name) provides a mechanism to change the +state_machine+ into the state specified by +state_name+ when the expected method is invoked.
-
#
-
# @see API#states
-
# @see StateMachine
-
# @see #when
-
#
-
# @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained.
-
#
-
# @example Using {#then} as syntactic sugar when specifying values to be returned and exceptions to be raised on consecutive invocations of the expected method.
-
# object = mock()
-
# object.stubs(:expected_method).returns(1, 2).then.raises(Exception).then.returns(4)
-
# object.expected_method # => 1
-
# object.expected_method # => 2
-
# object.expected_method # => raises exception of class Exception
-
# object.expected_method # => 4
-
#
-
# @example Using {#then} to change the +state+ of a +state_machine+ on the invocation of an expected method.
-
# power = states('power').starts_as('off')
-
#
-
# radio = mock('radio')
-
# radio.expects(:switch_on).then(power.is('on'))
-
# radio.expects(:select_channel).with('BBC Radio 4').when(power.is('on'))
-
# radio.expects(:adjust_volume).with(+5).when(power.is('on'))
-
# radio.expects(:select_channel).with('BBC World Service').when(power.is('on'))
-
# radio.expects(:adjust_volume).with(-5).when(power.is('on'))
-
# radio.expects(:switch_off).then(power.is('off'))
-
1
def then(*parameters)
-
if parameters.length == 1
-
state = parameters.first
-
add_side_effect(ChangeStateSideEffect.new(state))
-
end
-
self
-
end
-
-
# Constrains the expectation to occur only when the +state_machine+ is in the state specified by +state_name+.
-
#
-
# @param [StateMachine::StatePredicate] state_machine.is(state_name) provides a mechanism to determine whether the +state_machine+ is in the state specified by +state_name+ when the expected method is invoked.
-
# @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained.
-
#
-
# @see API#states
-
# @see StateMachine
-
# @see #then
-
#
-
# @example Using {#when} to only allow invocation of methods when "power" state machine is in the "on" state.
-
# power = states('power').starts_as('off')
-
#
-
# radio = mock('radio')
-
# radio.expects(:switch_on).then(power.is('on'))
-
# radio.expects(:select_channel).with('BBC Radio 4').when(power.is('on'))
-
# radio.expects(:adjust_volume).with(+5).when(power.is('on'))
-
# radio.expects(:select_channel).with('BBC World Service').when(power.is('on'))
-
# radio.expects(:adjust_volume).with(-5).when(power.is('on'))
-
# radio.expects(:switch_off).then(power.is('off'))
-
1
def when(state_predicate)
-
add_ordering_constraint(InStateOrderingConstraint.new(state_predicate))
-
self
-
end
-
-
# Constrains the expectation so that it must be invoked at the current point in the +sequence+.
-
#
-
# To expect a sequence of invocations, write the expectations in order and add the +in_sequence(sequence)+ clause to each one.
-
#
-
# Expectations in a +sequence+ can have any invocation count.
-
#
-
# If an expectation in a sequence is stubbed, rather than expected, it can be skipped in the +sequence+.
-
#
-
# An expected method can appear in multiple sequences.
-
#
-
# @param [*Array<Sequence>] sequences sequences in which expected method should appear.
-
# @return [Expectation] the same expectation, thereby allowing invocations of other {Expectation} methods to be chained.
-
#
-
# @see API#sequence
-
#
-
# @example Ensure methods are invoked in a specified order.
-
# breakfast = sequence('breakfast')
-
#
-
# egg = mock('egg')
-
# egg.expects(:crack).in_sequence(breakfast)
-
# egg.expects(:fry).in_sequence(breakfast)
-
# egg.expects(:eat).in_sequence(breakfast)
-
1
def in_sequence(*sequences)
-
sequences.each { |sequence| add_in_sequence_ordering_constraint(sequence) }
-
self
-
end
-
-
# @private
-
1
attr_reader :backtrace
-
-
# @private
-
1
def initialize(mock, expected_method_name, backtrace = nil)
-
98
@mock = mock
-
98
@method_matcher = MethodMatcher.new(expected_method_name.to_sym)
-
98
@parameters_matcher = ParametersMatcher.new
-
98
@ordering_constraints = []
-
98
@side_effects = []
-
98
@cardinality, @invocation_count = Cardinality.exactly(1), 0
-
98
@return_values = ReturnValues.new
-
98
@yield_parameters = YieldParameters.new
-
98
@backtrace = backtrace || caller
-
end
-
-
# @private
-
1
def add_ordering_constraint(ordering_constraint)
-
@ordering_constraints << ordering_constraint
-
end
-
-
# @private
-
1
def add_in_sequence_ordering_constraint(sequence)
-
sequence.constrain_as_next_in_sequence(self)
-
end
-
-
# @private
-
1
def add_side_effect(side_effect)
-
@side_effects << side_effect
-
end
-
-
# @private
-
1
def perform_side_effects
-
283
@side_effects.each { |side_effect| side_effect.perform }
-
end
-
-
# @private
-
1
def in_correct_order?
-
325
@ordering_constraints.all? { |ordering_constraint| ordering_constraint.allows_invocation_now? }
-
end
-
-
# @private
-
1
def matches_method?(method_name)
-
100
@method_matcher.match?(method_name)
-
end
-
-
# @private
-
1
def match?(actual_method_name, *actual_parameters)
-
328
@method_matcher.match?(actual_method_name) && @parameters_matcher.match?(actual_parameters) && in_correct_order?
-
end
-
-
# @private
-
1
def invocations_allowed?
-
283
@cardinality.invocations_allowed?(@invocation_count)
-
end
-
-
# @private
-
1
def satisfied?
-
@cardinality.satisfied?(@invocation_count)
-
end
-
-
# @private
-
1
def invoke
-
283
@invocation_count += 1
-
283
perform_side_effects()
-
283
if block_given? then
-
@yield_parameters.next_invocation.each do |yield_parameters|
-
yield(*yield_parameters)
-
end
-
end
-
283
@return_values.next
-
end
-
-
# @private
-
1
def verified?(assertion_counter = nil)
-
98
assertion_counter.increment if assertion_counter && @cardinality.needs_verifying?
-
98
@cardinality.verified?(@invocation_count)
-
end
-
-
# @private
-
1
def used?
-
@cardinality.used?(@invocation_count)
-
end
-
-
# @private
-
1
def mocha_inspect
-
message = "#{@cardinality.mocha_inspect}, "
-
message << case @invocation_count
-
when 0 then "not yet invoked"
-
when 1 then "invoked once"
-
when 2 then "invoked twice"
-
else "invoked #{@invocation_count} times"
-
end
-
message << ": "
-
message << method_signature
-
message << "; #{@ordering_constraints.map { |oc| oc.mocha_inspect }.join("; ")}" unless @ordering_constraints.empty?
-
message
-
end
-
-
# @private
-
1
def method_signature
-
"#{@mock.mocha_inspect}.#{@method_matcher.mocha_inspect}#{@parameters_matcher.mocha_inspect}"
-
end
-
-
end
-
-
end
-
1
module Mocha
-
# Default exception class raised when an unexpected invocation or an unsatisfied expectation occurs.
-
#
-
# Authors of test libraries may use +Mocha::ExpectationErrorFactory+ to have Mocha raise a different exception.
-
#
-
# @see Mocha::ExpectationErrorFactory
-
1
class ExpectationError < Exception; end
-
end
-
1
require 'mocha/backtrace_filter'
-
1
require 'mocha/expectation_error'
-
-
1
module Mocha
-
-
# This factory determines what class of exception should be raised when Mocha detects a test failure.
-
#
-
# This class should only be used by authors of test libraries and not by typical "users" of Mocha.
-
#
-
# For example, it is used by +Mocha::Integration::MiniTest::Adapter+ in order to have Mocha raise a +MiniTest::Assertion+ which can then be sensibly handled by +MiniTest::Unit::TestCase+.
-
#
-
# @see Mocha::Integration::MiniTest::Adapter
-
1
class ExpectationErrorFactory
-
1
class << self
-
# @!attribute exception_class
-
# Determines what class of exception should be raised when Mocha detects a test failure.
-
#
-
# This attribute may be set by authors of test libraries in order to have Mocha raise exceptions of a specific class when there is an unexpected invocation or an unsatisfied expectation.
-
#
-
# By default a +Mocha::ExpectationError+ will be raised.
-
#
-
# @return [Exception] class of exception to be raised when an expectation error occurs
-
# @see Mocha::ExpectationError
-
1
attr_accessor :exception_class
-
-
# @private
-
1
def build(message = nil, backtrace = [])
-
self.exception_class ||= ExpectationError
-
exception = exception_class.new(message)
-
filter = BacktraceFilter.new
-
exception.set_backtrace(filter.filtered(backtrace))
-
exception
-
end
-
end
-
end
-
end
-
1
module Mocha
-
-
1
class ExpectationList
-
-
1
def initialize
-
83
@expectations = []
-
end
-
-
1
def add(expectation)
-
98
@expectations.unshift(expectation)
-
98
expectation
-
end
-
-
1
def remove_all_matching_method(method_name)
-
185
@expectations.reject! { |expectation| expectation.matches_method?(method_name) }
-
end
-
-
1
def matches_method?(method_name)
-
@expectations.any? { |expectation| expectation.matches_method?(method_name) }
-
end
-
-
1
def match(method_name, *arguments)
-
matching_expectations(method_name, *arguments).first
-
end
-
-
1
def match_allowing_invocation(method_name, *arguments)
-
566
matching_expectations(method_name, *arguments).detect { |e| e.invocations_allowed? }
-
end
-
-
1
def verified?(assertion_counter = nil)
-
181
@expectations.all? { |expectation| expectation.verified?(assertion_counter) }
-
end
-
-
1
def to_a
-
83
@expectations
-
end
-
-
1
def to_set
-
@expectations.to_set
-
end
-
-
1
def length
-
@expectations.length
-
end
-
-
1
def any?
-
85
@expectations.any?
-
end
-
-
1
private
-
-
1
def matching_expectations(method_name, *arguments)
-
611
@expectations.select { |e| e.match?(method_name, *arguments) }
-
end
-
-
end
-
-
end
-
1
require 'mocha/mockery'
-
-
1
module Mocha
-
-
# Integration hooks for test library authors.
-
#
-
# The methods in this module should be called from test libraries wishing to integrate with Mocha.
-
#
-
# This module is provided as part of the +Mocha::API+ module and is therefore part of the public API, but should only be used by authors of test libraries and not by typical "users" of Mocha.
-
#
-
# Integration with Test::Unit and MiniTest are provided as part of Mocha, because they are (or were once) part of the Ruby standard library. Integration with other test libraries is not provided as *part* of Mocha, but is supported by means of the methods in this module.
-
#
-
# See the code in the +Adapter+ modules for examples of how to use the methods in this module. +Mocha::ExpectationErrorFactory+ may be used if you want +Mocha+ to raise a different type of exception.
-
#
-
# @see Mocha::Integration::TestUnit::Adapter
-
# @see Mocha::Integration::MiniTest::Adapter
-
# @see Mocha::ExpectationErrorFactory
-
# @see Mocha::API
-
1
module Hooks
-
# Prepares Mocha before a test (only for use by authors of test libraries).
-
#
-
# This method should be called before each individual test starts (including before any "setup" code).
-
1
def mocha_setup
-
end
-
-
# Verifies that all mock expectations have been met (only for use by authors of test libraries).
-
#
-
# This is equivalent to a series of "assertions".
-
#
-
# This method should be called at the end of each individual test, before it has been determined whether or not the test has passed.
-
1
def mocha_verify(assertion_counter = nil)
-
2856
Mockery.instance.verify(assertion_counter)
-
end
-
-
# Resets Mocha after a test (only for use by authors of test libraries).
-
#
-
# This method should be called after each individual test has finished (including after any "teardown" code).
-
1
def mocha_teardown
-
2856
Mockery.instance.teardown
-
2856
Mockery.reset_instance
-
end
-
end
-
end
-
1
module Mocha
-
-
1
class InStateOrderingConstraint
-
-
1
def initialize(state_predicate)
-
@state_predicate = state_predicate
-
end
-
-
1
def allows_invocation_now?
-
@state_predicate.active?
-
end
-
-
1
def mocha_inspect
-
"when #{@state_predicate.mocha_inspect}"
-
end
-
-
end
-
-
end
-
1
require 'date'
-
-
1
module Mocha
-
-
1
module ObjectMethods
-
1
def mocha_inspect
-
address = self.__id__ * 2
-
address += 0x100000000 if address < 0
-
inspect =~ /#</ ? "#<#{self.class}:0x#{'%x' % address}>" : inspect
-
end
-
end
-
-
1
module StringMethods
-
1
def mocha_inspect
-
inspect.gsub(/\"/, "'")
-
end
-
end
-
-
1
module ArrayMethods
-
1
def mocha_inspect
-
"[#{collect { |member| member.mocha_inspect }.join(', ')}]"
-
end
-
end
-
-
1
module HashMethods
-
1
def mocha_inspect
-
"{#{collect { |key, value| "#{key.mocha_inspect} => #{value.mocha_inspect}" }.join(', ')}}"
-
end
-
end
-
-
1
module TimeMethods
-
1
def mocha_inspect
-
"#{inspect} (#{to_f} secs)"
-
end
-
end
-
-
1
module DateMethods
-
1
def mocha_inspect
-
to_s
-
end
-
end
-
-
end
-
-
1
class Object
-
1
include Mocha::ObjectMethods
-
end
-
-
1
class String
-
1
include Mocha::StringMethods
-
end
-
-
1
class Array
-
1
include Mocha::ArrayMethods
-
end
-
-
1
class Hash
-
1
include Mocha::HashMethods
-
end
-
-
1
class Time
-
1
include Mocha::TimeMethods
-
end
-
-
1
class Date
-
1
include Mocha::DateMethods
-
end
-
1
require 'mocha/class_method'
-
-
1
module Mocha
-
-
1
class InstanceMethod < ClassMethod
-
-
1
def method_exists?(method)
-
27
return true if stubbee.public_methods(false).include?(method)
-
16
return true if stubbee.protected_methods(false).include?(method)
-
16
return true if stubbee.private_methods(false).include?(method)
-
16
return false
-
end
-
-
end
-
-
end
-
1
class Object
-
-
# :stopdoc:
-
-
1
alias_method :__is_a__, :is_a?
-
-
# :startdoc:
-
-
end
-
1
module Mocha
-
-
1
class Logger
-
-
1
def initialize(io)
-
@io = io
-
end
-
-
1
def warn(message)
-
@io.puts "WARNING: #{message}"
-
end
-
-
end
-
-
end
-
1
module Mocha
-
-
1
class MethodMatcher
-
-
1
attr_reader :expected_method_name
-
-
1
def initialize(expected_method_name)
-
98
@expected_method_name = expected_method_name
-
end
-
-
1
def match?(actual_method_name)
-
428
@expected_method_name == actual_method_name.to_sym
-
end
-
-
1
def mocha_inspect
-
"#{@expected_method_name}"
-
end
-
-
end
-
-
end
-
1
require 'metaclass'
-
1
require 'mocha/expectation'
-
1
require 'mocha/expectation_list'
-
1
require 'mocha/names'
-
1
require 'mocha/method_matcher'
-
1
require 'mocha/parameters_matcher'
-
1
require 'mocha/unexpected_invocation'
-
1
require 'mocha/argument_iterator'
-
1
require 'mocha/expectation_error_factory'
-
-
1
module Mocha
-
-
# Traditional mock object.
-
#
-
# All methods return an {Expectation} which can be further modified by methods on {Expectation}.
-
1
class Mock
-
-
# Adds an expectation that the specified method must be called exactly once with any parameters.
-
#
-
# @param [Symbol,String] method_name name of expected method
-
# @param [Hash] expected_methods_vs_return_values expected method name symbols as keys and corresponding return values as values - these expectations are setup as if {#expects} were called multiple times.
-
#
-
# @overload def expects(method_name)
-
# @overload def expects(expected_methods_vs_return_values)
-
# @return [Expectation] last-built expectation which can be further modified by methods on {Expectation}.
-
#
-
# @example Expected method invoked once so no error raised
-
# object = mock()
-
# object.expects(:expected_method)
-
# object.expected_method
-
#
-
# @example Expected method not invoked so error raised
-
# object = mock()
-
# object.expects(:expected_method)
-
# # error raised when test completes, because expected_method not called exactly once
-
#
-
# @example Expected method invoked twice so error raised
-
# object = mock()
-
# object.expects(:expected_method)
-
# object.expected_method
-
# object.expected_method # => error raised when expected method invoked second time
-
#
-
# @example Setup multiple expectations using +expected_methods_vs_return_values+.
-
# object = mock()
-
# object.expects(:expected_method_one => :result_one, :expected_method_two => :result_two)
-
#
-
# # is exactly equivalent to
-
#
-
# object = mock()
-
# object.expects(:expected_method_one).returns(:result_one)
-
# object.expects(:expected_method_two).returns(:result_two)
-
1
def expects(method_name_or_hash, backtrace = nil)
-
33
iterator = ArgumentIterator.new(method_name_or_hash)
-
33
iterator.each { |*args|
-
32
method_name = args.shift
-
32
ensure_method_not_already_defined(method_name)
-
32
expectation = Expectation.new(self, method_name, backtrace)
-
32
expectation.returns(args.shift) if args.length > 0
-
32
@expectations.add(expectation)
-
}
-
end
-
-
# Adds an expectation that the specified method may be called any number of times with any parameters.
-
#
-
# @param [Symbol,String] method_name name of stubbed method
-
# @param [Hash] stubbed_methods_vs_return_values stubbed method name symbols as keys and corresponding return values as values - these stubbed methods are setup as if {#stubs} were called multiple times.
-
#
-
# @overload def stubs(method_name)
-
# @overload def stubs(stubbed_methods_vs_return_values)
-
# @return [Expectation] last-built expectation which can be further modified by methods on {Expectation}.
-
#
-
# @example No error raised however many times stubbed method is invoked
-
# object = mock()
-
# object.stubs(:stubbed_method)
-
# object.stubbed_method
-
# object.stubbed_method
-
# # no error raised
-
#
-
# @example Setup multiple expectations using +stubbed_methods_vs_return_values+.
-
# object = mock()
-
# object.stubs(:stubbed_method_one => :result_one, :stubbed_method_two => :result_two)
-
#
-
# # is exactly equivalent to
-
#
-
# object = mock()
-
# object.stubs(:stubbed_method_one).returns(:result_one)
-
# object.stubs(:stubbed_method_two).returns(:result_two)
-
1
def stubs(method_name_or_hash, backtrace = nil)
-
66
iterator = ArgumentIterator.new(method_name_or_hash)
-
66
iterator.each { |*args|
-
66
method_name = args.shift
-
66
ensure_method_not_already_defined(method_name)
-
66
expectation = Expectation.new(self, method_name, backtrace)
-
66
expectation.at_least(0)
-
66
expectation.returns(args.shift) if args.length > 0
-
66
@expectations.add(expectation)
-
}
-
end
-
-
# Removes the specified stubbed method (added by calls to {#expects} or {#stubs}) and all expectations associated with it.
-
#
-
# @param [Symbol] method_name name of method to unstub.
-
#
-
# @example Invoking an unstubbed method causes error to be raised
-
# object = mock('mock') do
-
# object.stubs(:stubbed_method).returns(:result_one)
-
# object.stubbed_method # => :result_one
-
# object.unstub(:stubbed_method)
-
# object.stubbed_method # => unexpected invocation: #<Mock:mock>.stubbed_method()
-
1
def unstub(method_name)
-
85
@expectations.remove_all_matching_method(method_name)
-
end
-
-
# Constrains the {Mock} instance so that it can only expect or stub methods to which +responder+ responds. The constraint is only applied at method invocation time.
-
#
-
# A +NoMethodError+ will be raised if the +responder+ does not +#respond_to?+ a method invocation (even if the method has been expected or stubbed).
-
#
-
# The {Mock} instance will delegate its +#respond_to?+ method to the +responder+.
-
#
-
# @param [Object, #respond_to?] responder an object used to determine whether {Mock} instance should +#respond_to?+ to an invocation.
-
# @return [Mock] the same {Mock} instance, thereby allowing invocations of other {Mock} methods to be chained.
-
#
-
# @example Normal mocking
-
# sheep = mock('sheep')
-
# sheep.expects(:chew)
-
# sheep.expects(:foo)
-
# sheep.respond_to?(:chew) # => true
-
# sheep.respond_to?(:foo) # => true
-
# sheep.chew
-
# sheep.foo
-
# # no error raised
-
#
-
# @example Using {#responds_like} with an instance method
-
# class Sheep
-
# def chew(grass); end
-
# end
-
#
-
# sheep = mock('sheep')
-
# sheep.responds_like(Sheep.new)
-
# sheep.expects(:chew)
-
# sheep.expects(:foo)
-
# sheep.respond_to?(:chew) # => true
-
# sheep.respond_to?(:foo) # => false
-
# sheep.chew
-
# sheep.foo # => raises NoMethodError exception
-
#
-
# @example Using {#responds_like} with a class method
-
# class Sheep
-
# def self.number_of_legs; end
-
# end
-
#
-
# sheep_class = mock('sheep_class')
-
# sheep_class.responds_like(Sheep)
-
# sheep_class.stubs(:number_of_legs).returns(4)
-
# sheep_class.expects(:foo)
-
# sheep_class.respond_to?(:number_of_legs) # => true
-
# sheep_class.respond_to?(:foo) # => false
-
# assert_equal 4, sheep_class.number_of_legs
-
# sheep_class.foo # => raises NoMethodError exception
-
1
def responds_like(responder)
-
@responder = responder
-
self
-
end
-
-
# @private
-
1
def initialize(mockery, name = nil, &block)
-
83
@mockery = mockery
-
83
@name = name || DefaultName.new(self)
-
83
@expectations = ExpectationList.new
-
83
@everything_stubbed = false
-
83
@responder = nil
-
83
instance_eval(&block) if block
-
end
-
-
# @private
-
1
attr_reader :everything_stubbed
-
-
1
alias_method :__expects__, :expects
-
-
1
alias_method :__stubs__, :stubs
-
-
1
alias_method :quacks_like, :responds_like
-
-
# @private
-
1
def __expectations__
-
83
@expectations
-
end
-
-
# @private
-
1
def stub_everything
-
@everything_stubbed = true
-
end
-
-
# @private
-
1
def method_missing(symbol, *arguments, &block)
-
283
if @responder and not @responder.respond_to?(symbol)
-
raise NoMethodError, "undefined method `#{symbol}' for #{self.mocha_inspect} which responds like #{@responder.mocha_inspect}"
-
end
-
283
if matching_expectation_allowing_invocation = @expectations.match_allowing_invocation(symbol, *arguments)
-
283
matching_expectation_allowing_invocation.invoke(&block)
-
else
-
if (matching_expectation = @expectations.match(symbol, *arguments)) || (!matching_expectation && !@everything_stubbed)
-
matching_expectation.invoke(&block) if matching_expectation
-
message = UnexpectedInvocation.new(self, symbol, *arguments).to_s
-
message << @mockery.mocha_inspect
-
raise ExpectationErrorFactory.build(message, caller)
-
end
-
end
-
end
-
-
# @private
-
1
def respond_to?(symbol, include_private = false)
-
if @responder then
-
if @responder.method(:respond_to?).arity > 1
-
@responder.respond_to?(symbol, include_private)
-
else
-
@responder.respond_to?(symbol)
-
end
-
else
-
@everything_stubbed || @expectations.matches_method?(symbol)
-
end
-
end
-
-
# @private
-
1
def __verified__?(assertion_counter = nil)
-
83
@expectations.verified?(assertion_counter)
-
end
-
-
# @private
-
1
def mocha_inspect
-
@name.mocha_inspect
-
end
-
-
# @private
-
1
def inspect
-
mocha_inspect
-
end
-
-
# @private
-
1
def ensure_method_not_already_defined(method_name)
-
98
self.__metaclass__.send(:undef_method, method_name) if self.__metaclass__.method_defined?(method_name)
-
end
-
-
# @private
-
1
def any_expectations?
-
85
@expectations.any?
-
end
-
-
end
-
-
end
-
1
require 'mocha/central'
-
1
require 'mocha/mock'
-
1
require 'mocha/names'
-
1
require 'mocha/state_machine'
-
1
require 'mocha/logger'
-
1
require 'mocha/configuration'
-
1
require 'mocha/stubbing_error'
-
1
require 'mocha/expectation_error_factory'
-
-
1
module Mocha
-
-
1
class Mockery
-
-
1
class << self
-
-
1
def instance
-
5892
@instance ||= new
-
end
-
-
1
def reset_instance
-
2856
@instance = nil
-
end
-
-
end
-
-
1
def named_mock(name, &block)
-
1
add_mock(Mock.new(self, Name.new(name), &block))
-
end
-
-
1
def unnamed_mock(&block)
-
add_mock(Mock.new(self, &block))
-
end
-
-
1
def mock_impersonating(object, &block)
-
82
add_mock(Mock.new(self, ImpersonatingName.new(object), &block))
-
end
-
-
1
def mock_impersonating_any_instance_of(klass, &block)
-
add_mock(Mock.new(self, ImpersonatingAnyInstanceName.new(klass), &block))
-
end
-
-
1
def new_state_machine(name)
-
add_state_machine(StateMachine.new(name))
-
end
-
-
1
def verify(assertion_counter = nil)
-
2939
unless mocks.all? { |mock| mock.__verified__?(assertion_counter) }
-
message = "not all expectations were satisfied\n#{mocha_inspect}"
-
if unsatisfied_expectations.empty?
-
backtrace = caller
-
else
-
backtrace = unsatisfied_expectations[0].backtrace
-
end
-
raise ExpectationErrorFactory.build(message, backtrace)
-
end
-
2856
expectations.each do |e|
-
98
unless Mocha::Configuration.allow?(:stubbing_method_unnecessarily)
-
unless e.used?
-
on_stubbing_method_unnecessarily(e)
-
end
-
end
-
end
-
end
-
-
1
def teardown
-
2856
stubba.unstub_all
-
2856
reset
-
end
-
-
1
def stubba
-
2953
@stubba ||= Central.new
-
end
-
-
1
def mocks
-
5795
@mocks ||= []
-
end
-
-
1
def state_machines
-
@state_machines ||= []
-
end
-
-
1
def mocha_inspect
-
message = ""
-
message << "unsatisfied expectations:\n- #{unsatisfied_expectations.map { |e| e.mocha_inspect }.join("\n- ")}\n" unless unsatisfied_expectations.empty?
-
message << "satisfied expectations:\n- #{satisfied_expectations.map { |e| e.mocha_inspect }.join("\n- ")}\n" unless satisfied_expectations.empty?
-
message << "states:\n- #{state_machines.map { |sm| sm.mocha_inspect }.join("\n- ")}" unless state_machines.empty?
-
message
-
end
-
-
1
def on_stubbing(object, method)
-
97
method = RUBY_VERSION < '1.9' ? method.to_s : method.to_sym
-
97
unless Mocha::Configuration.allow?(:stubbing_non_existent_method)
-
unless object.method_exists?(method, include_public_methods = true)
-
on_stubbing_non_existent_method(object, method)
-
end
-
end
-
97
unless Mocha::Configuration.allow?(:stubbing_non_public_method)
-
if object.method_exists?(method, include_public_methods = false)
-
on_stubbing_non_public_method(object, method)
-
end
-
end
-
97
unless Mocha::Configuration.allow?(:stubbing_method_on_nil)
-
97
if object.nil?
-
on_stubbing_method_on_nil(object, method)
-
end
-
end
-
97
unless Mocha::Configuration.allow?(:stubbing_method_on_non_mock_object)
-
on_stubbing_method_on_non_mock_object(object, method)
-
end
-
end
-
-
1
def on_stubbing_non_existent_method(object, method)
-
if Mocha::Configuration.prevent?(:stubbing_non_existent_method)
-
raise StubbingError.new("stubbing non-existent method: #{object.mocha_inspect}.#{method}", caller)
-
end
-
if Mocha::Configuration.warn_when?(:stubbing_non_existent_method)
-
logger.warn "stubbing non-existent method: #{object.mocha_inspect}.#{method}"
-
end
-
end
-
-
1
def on_stubbing_non_public_method(object, method)
-
if Mocha::Configuration.prevent?(:stubbing_non_public_method)
-
raise StubbingError.new("stubbing non-public method: #{object.mocha_inspect}.#{method}", caller)
-
end
-
if Mocha::Configuration.warn_when?(:stubbing_non_public_method)
-
logger.warn "stubbing non-public method: #{object.mocha_inspect}.#{method}"
-
end
-
end
-
-
1
def on_stubbing_method_on_nil(object, method)
-
if Mocha::Configuration.prevent?(:stubbing_method_on_nil)
-
raise StubbingError.new("stubbing method on nil: #{object.mocha_inspect}.#{method}", caller)
-
end
-
if Mocha::Configuration.warn_when?(:stubbing_method_on_nil)
-
logger.warn "stubbing method on nil: #{object.mocha_inspect}.#{method}"
-
end
-
end
-
-
1
def on_stubbing_method_on_non_mock_object(object, method)
-
if Mocha::Configuration.prevent?(:stubbing_method_on_non_mock_object)
-
raise StubbingError.new("stubbing method on non-mock object: #{object.mocha_inspect}.#{method}", caller)
-
end
-
if Mocha::Configuration.warn_when?(:stubbing_method_on_non_mock_object)
-
logger.warn "stubbing method on non-mock object: #{object.mocha_inspect}.#{method}"
-
end
-
end
-
-
1
def on_stubbing_method_unnecessarily(expectation)
-
if Mocha::Configuration.prevent?(:stubbing_method_unnecessarily)
-
raise StubbingError.new("stubbing method unnecessarily: #{expectation.method_signature}", expectation.backtrace)
-
end
-
if Mocha::Configuration.warn_when?(:stubbing_method_unnecessarily)
-
logger.warn "stubbing method unnecessarily: #{expectation.method_signature}"
-
end
-
end
-
-
1
attr_writer :logger
-
-
1
def logger
-
@logger ||= Logger.new($stderr)
-
end
-
-
-
1
private
-
-
1
def expectations
-
2939
mocks.map { |mock| mock.__expectations__.to_a }.flatten
-
end
-
-
1
def unsatisfied_expectations
-
expectations.reject { |e| e.verified? }
-
end
-
-
1
def satisfied_expectations
-
expectations.select { |e| e.verified? }
-
end
-
-
1
def add_mock(mock)
-
83
mocks << mock
-
83
mock
-
end
-
-
1
def add_state_machine(state_machine)
-
state_machines << state_machine
-
state_machine
-
end
-
-
1
def reset
-
2856
@stubba = nil
-
2856
@mocks = nil
-
2856
@state_machines = nil
-
end
-
-
end
-
-
end
-
1
require 'mocha/class_method'
-
-
1
module Mocha
-
-
1
class ModuleMethod < ClassMethod
-
-
1
def method_exists?(method)
-
return true if stubbee.public_methods(false).include?(method)
-
return true if stubbee.protected_methods(false).include?(method)
-
return true if stubbee.private_methods(false).include?(method)
-
return false
-
end
-
-
end
-
-
end
-
1
require 'mocha/module_method'
-
-
1
module Mocha
-
-
# @private
-
1
module ModuleMethods
-
-
1
def stubba_method
-
Mocha::ModuleMethod
-
end
-
-
end
-
-
end
-
1
module Mocha
-
-
1
class MultipleYields
-
-
1
attr_reader :parameter_groups
-
-
1
def initialize(*parameter_groups)
-
@parameter_groups = parameter_groups
-
end
-
-
1
def each
-
@parameter_groups.each do |parameter_group|
-
yield(parameter_group)
-
end
-
end
-
-
end
-
-
end
-
-
1
module Mocha
-
-
1
class ImpersonatingName
-
-
1
def initialize(object)
-
82
@object = object
-
end
-
-
1
def mocha_inspect
-
@object.mocha_inspect
-
end
-
-
end
-
-
1
class ImpersonatingAnyInstanceName
-
-
1
def initialize(klass)
-
@klass = klass
-
end
-
-
1
def mocha_inspect
-
"#<AnyInstance:#{@klass.mocha_inspect}>"
-
end
-
-
end
-
-
1
class Name
-
-
1
def initialize(name)
-
1
@name = name
-
end
-
-
1
def mocha_inspect
-
"#<Mock:#{@name}>"
-
end
-
-
end
-
-
1
class DefaultName
-
-
1
def initialize(mock)
-
@mock = mock
-
end
-
-
1
def mocha_inspect
-
address = @mock.__id__ * 2
-
address += 0x100000000 if address < 0
-
"#<Mock:0x#{'%x' % address}>"
-
end
-
-
end
-
-
end
-
1
module Mocha
-
-
1
class NoYields
-
-
1
def each
-
end
-
-
end
-
-
end
-
-
1
require 'mocha/mockery'
-
1
require 'mocha/instance_method'
-
1
require 'mocha/argument_iterator'
-
1
require 'mocha/expectation_error_factory'
-
-
1
module Mocha
-
-
# Methods added to all objects to allow mocking and stubbing on real (i.e. non-mock) objects.
-
#
-
# Both {#expects} and {#stubs} return an {Expectation} which can be further modified by methods on {Expectation}.
-
1
module ObjectMethods
-
-
# @private
-
1
alias_method :_method, :method
-
-
# @private
-
1
def mocha
-
549
@mocha ||= Mocha::Mockery.instance.mock_impersonating(self)
-
end
-
-
# @private
-
1
def reset_mocha
-
82
@mocha = nil
-
end
-
-
# @private
-
1
def stubba_method
-
27
Mocha::InstanceMethod
-
end
-
-
# @private
-
1
def stubba_object
-
97
self
-
end
-
-
# Adds an expectation that the specified method must be called exactly once with any parameters.
-
#
-
# The original implementation of the method is replaced during the test and then restored at the end of the test.
-
#
-
# @param [Symbol,String] method_name name of expected method
-
# @param [Hash] expected_methods_vs_return_values expected method name symbols as keys and corresponding return values as values - these expectations are setup as if {#expects} were called multiple times.
-
#
-
# @overload def expects(method_name)
-
# @overload def expects(expected_methods_vs_return_values)
-
# @return [Expectation] last-built expectation which can be further modified by methods on {Expectation}.
-
# @raise [StubbingError] if attempting to stub method which is not allowed.
-
#
-
# @example Setting up an expectation on a non-mock object.
-
# product = Product.new
-
# product.expects(:save).returns(true)
-
# assert_equal true, product.save
-
#
-
# @example Setting up multiple expectations on a non-mock object.
-
# product = Product.new
-
# product.expects(:valid? => true, :save => true)
-
#
-
# # exactly equivalent to
-
#
-
# product = Product.new
-
# product.expects(:valid?).returns(true)
-
# product.expects(:save).returns(true)
-
#
-
# @see Mock#expects
-
1
def expects(expected_methods_vs_return_values)
-
31
if expected_methods_vs_return_values.to_s =~ /the[^a-z]*spanish[^a-z]*inquisition/i
-
raise ExpectationErrorFactory.build('NOBODY EXPECTS THE SPANISH INQUISITION!')
-
end
-
31
if frozen?
-
raise StubbingError.new("can't stub method on frozen object: #{mocha_inspect}", caller)
-
end
-
31
expectation = nil
-
31
mockery = Mocha::Mockery.instance
-
31
iterator = ArgumentIterator.new(expected_methods_vs_return_values)
-
31
iterator.each { |*args|
-
31
method_name = args.shift
-
31
mockery.on_stubbing(self, method_name)
-
31
method = stubba_method.new(stubba_object, method_name)
-
31
mockery.stubba.stub(method)
-
31
expectation = mocha.expects(method_name, caller)
-
31
expectation.returns(args.shift) if args.length > 0
-
}
-
31
expectation
-
end
-
-
# Adds an expectation that the specified method may be called any number of times with any parameters.
-
#
-
# @param [Symbol,String] method_name name of stubbed method
-
# @param [Hash] stubbed_methods_vs_return_values stubbed method name symbols as keys and corresponding return values as values - these stubbed methods are setup as if {#stubs} were called multiple times.
-
#
-
# @overload def stubs(method_name)
-
# @overload def stubs(stubbed_methods_vs_return_values)
-
# @return [Expectation] last-built expectation which can be further modified by methods on {Expectation}.
-
# @raise [StubbingError] if attempting to stub method which is not allowed.
-
#
-
# @example Setting up a stubbed methods on a non-mock object.
-
# product = Product.new
-
# product.stubs(:save).returns(true)
-
# assert_equal true, product.save
-
#
-
# @example Setting up multiple stubbed methods on a non-mock object.
-
# product = Product.new
-
# product.stubs(:valid? => true, :save => true)
-
#
-
# # exactly equivalent to
-
#
-
# product = Product.new
-
# product.stubs(:valid?).returns(true)
-
# product.stubs(:save).returns(true)
-
#
-
# @see Mock#stubs
-
1
def stubs(stubbed_methods_vs_return_values)
-
66
if frozen?
-
raise StubbingError.new("can't stub method on frozen object: #{mocha_inspect}", caller)
-
end
-
66
expectation = nil
-
66
mockery = Mocha::Mockery.instance
-
66
iterator = ArgumentIterator.new(stubbed_methods_vs_return_values)
-
66
iterator.each { |*args|
-
66
method_name = args.shift
-
66
mockery.on_stubbing(self, method_name)
-
66
method = stubba_method.new(stubba_object, method_name)
-
66
mockery.stubba.stub(method)
-
66
expectation = mocha.stubs(method_name, caller)
-
66
expectation.returns(args.shift) if args.length > 0
-
}
-
66
expectation
-
end
-
-
# Removes the specified stubbed methods (added by calls to {#expects} or {#stubs}) and all expectations associated with them.
-
#
-
# Restores the original behaviour of the methods before they were stubbed.
-
#
-
# WARNING: If you {#unstub} a method which still has unsatisfied expectations, you may be removing the only way those expectations can be satisfied. Use {#unstub} with care.
-
#
-
# @param [Array<Symbol>] method_names names of methods to unstub.
-
#
-
# @example Stubbing and unstubbing a method on a real (non-mock) object.
-
# multiplier = Multiplier.new
-
# multiplier.double(2) # => 4
-
# multiplier.stubs(:double).raises # new behaviour defined
-
# multiplier.double(2) # => raises exception
-
# multiplier.unstub(:double) # original behaviour restored
-
# multiplier.double(2) # => 4
-
#
-
# @example Unstubbing multiple methods on a real (non-mock) object.
-
# multiplier.unstub(:double, :triple)
-
#
-
# # exactly equivalent to
-
#
-
# multiplier.unstub(:double)
-
# multiplier.unstub(:triple)
-
1
def unstub(*method_names)
-
mockery = Mocha::Mockery.instance
-
method_names.each do |method_name|
-
method = stubba_method.new(stubba_object, method_name)
-
mockery.stubba.unstub(method)
-
end
-
end
-
-
# @private
-
1
def method_exists?(method, include_public_methods = true)
-
if include_public_methods
-
return true if public_methods(include_superclass_methods = true).include?(method)
-
return true if respond_to?(method.to_sym)
-
end
-
return true if protected_methods(include_superclass_methods = true).include?(method)
-
return true if private_methods(include_superclass_methods = true).include?(method)
-
return false
-
end
-
-
end
-
-
end
-
1
module Mocha
-
-
# Used as parameters for {Expectation#with} to restrict the parameter values which will match the expectation. Can be nested.
-
1
module ParameterMatchers; end
-
-
end
-
-
1
require 'mocha/parameter_matchers/object'
-
-
1
require 'mocha/parameter_matchers/all_of'
-
1
require 'mocha/parameter_matchers/any_of'
-
1
require 'mocha/parameter_matchers/any_parameters'
-
1
require 'mocha/parameter_matchers/anything'
-
1
require 'mocha/parameter_matchers/equals'
-
1
require 'mocha/parameter_matchers/has_entry'
-
1
require 'mocha/parameter_matchers/has_entries'
-
1
require 'mocha/parameter_matchers/has_key'
-
1
require 'mocha/parameter_matchers/has_value'
-
1
require 'mocha/parameter_matchers/includes'
-
1
require 'mocha/parameter_matchers/instance_of'
-
1
require 'mocha/parameter_matchers/is_a'
-
1
require 'mocha/parameter_matchers/kind_of'
-
1
require 'mocha/parameter_matchers/not'
-
1
require 'mocha/parameter_matchers/optionally'
-
1
require 'mocha/parameter_matchers/regexp_matches'
-
1
require 'mocha/parameter_matchers/responds_with'
-
1
require 'mocha/parameter_matchers/yaml_equivalent'
-
1
require 'mocha/parameter_matchers/query_string'
-
1
require 'mocha/parameter_matchers/base'
-
-
1
module Mocha
-
-
1
module ParameterMatchers
-
-
# Matches if all +matchers+ match.
-
#
-
# @param [*Array<Base>] parameter_matchers parameter matchers.
-
# @return [AllOf] parameter matcher.
-
#
-
# @see Expectation#with
-
#
-
# @example All parameter matchers match.
-
# object = mock()
-
# object.expects(:method_1).with(all_of(includes(1), includes(3)))
-
# object.method_1([1, 3])
-
# # no error raised
-
#
-
# @example One of the parameter matchers does not match.
-
# object = mock()
-
# object.expects(:method_1).with(all_of(includes(1), includes(3)))
-
# object.method_1([1, 2])
-
# # error raised, because method_1 was not called with object including 1 and 3
-
1
def all_of(*matchers)
-
AllOf.new(*matchers)
-
end
-
-
# Parameter matcher which combines a number of other matchers using a logical AND.
-
1
class AllOf < Base
-
-
# @private
-
1
def initialize(*matchers)
-
@matchers = matchers
-
end
-
-
# @private
-
1
def matches?(available_parameters)
-
parameter = available_parameters.shift
-
@matchers.all? { |matcher| matcher.to_matcher.matches?([parameter]) }
-
end
-
-
# @private
-
1
def mocha_inspect
-
"all_of(#{@matchers.map { |matcher| matcher.mocha_inspect }.join(", ") })"
-
end
-
-
end
-
-
end
-
-
end
-
1
require 'mocha/parameter_matchers/base'
-
-
1
module Mocha
-
-
1
module ParameterMatchers
-
-
# Matches if any +matchers+ match.
-
#
-
# @param [*Array<Base>] parameter_matchers parameter matchers.
-
# @return [AnyOf] parameter matcher.
-
#
-
# @see Expectation#with
-
#
-
# @example One parameter matcher matches.
-
# object = mock()
-
# object.expects(:method_1).with(any_of(1, 3))
-
# object.method_1(1)
-
# # no error raised
-
#
-
# @example The other parameter matcher matches.
-
# object = mock()
-
# object.expects(:method_1).with(any_of(1, 3))
-
# object.method_1(3)
-
# # no error raised
-
#
-
# @example Neither parameter matcher matches.
-
# object = mock()
-
# object.expects(:method_1).with(any_of(1, 3))
-
# object.method_1(2)
-
# # error raised, because method_1 was not called with 1 or 3
-
1
def any_of(*matchers)
-
AnyOf.new(*matchers)
-
end
-
-
# Parameter matcher which combines a number of other matchers using a logical OR.
-
1
class AnyOf < Base
-
-
# @private
-
1
def initialize(*matchers)
-
@matchers = matchers
-
end
-
-
# @private
-
1
def matches?(available_parameters)
-
parameter = available_parameters.shift
-
@matchers.any? { |matcher| matcher.to_matcher.matches?([parameter]) }
-
end
-
-
# @private
-
1
def mocha_inspect
-
"any_of(#{@matchers.map { |matcher| matcher.mocha_inspect }.join(", ") })"
-
end
-
-
end
-
-
end
-
-
end
-
1
require 'mocha/parameter_matchers/base'
-
-
1
module Mocha
-
-
1
module ParameterMatchers
-
-
# Matches any parameters. This is used as the default for a newly built expectation.
-
#
-
# @return [AnyParameters] parameter matcher.
-
#
-
# @see Expectation#with
-
#
-
# @example Any parameters will match.
-
# object = mock()
-
# object.expects(:method_1).with(any_parameters)
-
# object.method_1(1, 2, 3, 4)
-
# # no error raised
-
#
-
# object = mock()
-
# object.expects(:method_1).with(any_parameters)
-
# object.method_1(5, 6, 7, 8, 9, 0)
-
# # no error raised
-
1
def any_parameters
-
AnyParameters.new
-
end
-
-
# Parameter matcher which always matches whatever the parameters.
-
1
class AnyParameters < Base
-
-
# @private
-
1
def matches?(available_parameters)
-
314
while available_parameters.length > 0 do
-
3
available_parameters.shift
-
end
-
314
return true
-
end
-
-
# @private
-
1
def mocha_inspect
-
"any_parameters"
-
end
-
-
end
-
-
end
-
-
end
-
1
require 'mocha/parameter_matchers/base'
-
-
1
module Mocha
-
-
1
module ParameterMatchers
-
-
# Matches any object.
-
#
-
# @return [Anything] parameter matcher.
-
#
-
# @see Expectation#with
-
#
-
# @example Any object will match.
-
# object = mock()
-
# object.expects(:method_1).with(anything)
-
# object.method_1('foo')
-
# object.method_1(789)
-
# object.method_1(:bar)
-
# # no error raised
-
1
def anything
-
Anything.new
-
end
-
-
# Parameter matcher which always matches a single parameter.
-
1
class Anything < Base
-
-
# @private
-
1
def matches?(available_parameters)
-
available_parameters.shift
-
return true
-
end
-
-
# @private
-
1
def mocha_inspect
-
"anything"
-
end
-
-
end
-
-
end
-
-
end
-
1
module Mocha
-
-
1
module ParameterMatchers
-
-
# @abstract Subclass and implement +#matches?+ and +#mocha_inspect+ to define a custom matcher. Also add a suitably named instance method to {ParameterMatchers} to build an instance of the new matcher c.f. {#equals}.
-
1
class Base
-
-
# @private
-
1
def to_matcher
-
314
self
-
end
-
-
# A shorthand way of combining two matchers when both must match.
-
#
-
# Returns a new {AllOf} parameter matcher combining two matchers using a logical AND.
-
#
-
# This shorthand will not work with an implicit equals match. Instead, an explicit {Equals} matcher should be used.
-
#
-
# @param [Base] matcher parameter matcher.
-
# @return [AllOf] parameter matcher.
-
#
-
# @see Expectation#with
-
#
-
# @example Alternative ways to combine matchers with a logical AND.
-
# object = mock()
-
# object.expects(:run).with(all_of(has_key(:foo), has_key(:bar)))
-
# object.run(:foo => 'foovalue', :bar => 'barvalue')
-
#
-
# # is exactly equivalent to
-
#
-
# object.expects(:run).with(has_key(:foo) & has_key(:bar))
-
# object.run(:foo => 'foovalue', :bar => 'barvalue)
-
1
def &(matcher)
-
AllOf.new(self, matcher)
-
end
-
-
# A shorthand way of combining two matchers when at least one must match.
-
#
-
# Returns a new +AnyOf+ parameter matcher combining two matchers using a logical OR.
-
#
-
# This shorthand will not work with an implicit equals match. Instead, an explicit {Equals} matcher should be used.
-
#
-
# @param [Base] matcher parameter matcher.
-
# @return [AnyOf] parameter matcher.
-
#
-
# @see Expectation#with
-
#
-
# @example Alternative ways to combine matchers with a logical OR.
-
# object = mock()
-
# object.expects(:run).with(any_of(has_key(:foo), has_key(:bar)))
-
# object.run(:foo => 'foovalue')
-
#
-
# # is exactly equivalent to
-
#
-
# object.expects(:run).with(has_key(:foo) | has_key(:bar))
-
# object.run(:foo => 'foovalue')
-
#
-
# @example Using an explicit {Equals} matcher in combination with {#|}.
-
# object.expects(:run).with(equals(1) | equals(2))
-
# object.run(1) # passes
-
# object.run(2) # passes
-
# object.run(3) # fails
-
1
def |(matcher)
-
AnyOf.new(self, matcher)
-
end
-
-
end
-
-
end
-
-
end
-
1
require 'mocha/parameter_matchers/base'
-
-
1
module Mocha
-
-
1
module ParameterMatchers
-
-
# Matches any +Object+ equalling +value+.
-
#
-
# @param [Object] value expected value.
-
# @return [Equals] parameter matcher.
-
#
-
# @see Expectation#with
-
# @see Object#==
-
#
-
# @example Actual parameter equals expected parameter.
-
# object = mock()
-
# object.expects(:method_1).with(equals(2))
-
# object.method_1(2)
-
# # no error raised
-
#
-
# @example Actual parameter does not equal expected parameter.
-
# object = mock()
-
# object.expects(:method_1).with(equals(2))
-
# object.method_1(3)
-
# # error raised, because method_1 was not called with an +Object+ that equals 3
-
1
def equals(value)
-
Equals.new(value)
-
end
-
-
# Parameter matcher which matches when actual parameter equals expected value.
-
1
class Equals < Base
-
-
# @private
-
1
def initialize(value)
-
28
@value = value
-
end
-
-
# @private
-
1
def matches?(available_parameters)
-
28
parameter = available_parameters.shift
-
28
parameter == @value
-
end
-
-
# @private
-
1
def mocha_inspect
-
@value.mocha_inspect
-
end
-
-
end
-
-
end
-
-
end
-
1
require 'mocha/parameter_matchers/base'
-
1
require 'mocha/parameter_matchers/all_of'
-
1
require 'mocha/parameter_matchers/has_entry'
-
-
1
module Mocha
-
-
1
module ParameterMatchers
-
-
# Matches +Hash+ containing all +entries+.
-
#
-
# @param [Hash] entries expected +Hash+ entries.
-
# @return [HasEntries] parameter matcher.
-
#
-
# @see Expectation#with
-
#
-
# @example Actual parameter contains all expected entries.
-
# object = mock()
-
# object.expects(:method_1).with(has_entries('key_1' => 1, 'key_2' => 2))
-
# object.method_1('key_1' => 1, 'key_2' => 2, 'key_3' => 3)
-
# # no error raised
-
#
-
# @example Actual parameter does not contain all expected entries.
-
# object = mock()
-
# object.expects(:method_1).with(has_entries('key_1' => 1, 'key_2' => 2))
-
# object.method_1('key_1' => 1, 'key_2' => 99)
-
# # error raised, because method_1 was not called with Hash containing entries: 'key_1' => 1, 'key_2' => 2
-
1
def has_entries(entries)
-
HasEntries.new(entries)
-
end
-
-
# Parameter matcher which matches when actual parameter contains all expected +Hash+ entries.
-
1
class HasEntries < Base
-
-
# @private
-
1
def initialize(entries)
-
@entries = entries
-
end
-
-
# @private
-
1
def matches?(available_parameters)
-
parameter = available_parameters.shift
-
has_entry_matchers = @entries.map { |key, value| HasEntry.new(key, value) }
-
AllOf.new(*has_entry_matchers).matches?([parameter])
-
end
-
-
# @private
-
1
def mocha_inspect
-
"has_entries(#{@entries.mocha_inspect})"
-
end
-
-
end
-
-
end
-
-
end
-
1
require 'mocha/parameter_matchers/base'
-
-
1
module Mocha
-
-
1
module ParameterMatchers
-
-
# Matches +Hash+ containing entry with +key+ and +value+.
-
#
-
# @overload def has_entry(key, value)
-
# @param [Object] key key for entry.
-
# @param [Object] value value for entry.
-
# @overload def has_entry(single_entry_hash)
-
# @param [Hash] single_entry_hash +Hash+ with single entry.
-
# @raise [ArgumentError] if +single_entry_hash+ does not contain exactly one entry.
-
#
-
# @return [HasEntry] parameter matcher.
-
#
-
# @see Expectation#with
-
#
-
# @example Actual parameter contains expected entry supplied as key and value.
-
# object = mock()
-
# object.expects(:method_1).with(has_entry('key_1', 1))
-
# object.method_1('key_1' => 1, 'key_2' => 2)
-
# # no error raised
-
#
-
# @example Actual parameter contains expected entry supplied as +Hash+ entry.
-
# object = mock()
-
# object.expects(:method_1).with(has_entry('key_1' => 1))
-
# object.method_1('key_1' => 1, 'key_2' => 2)
-
# # no error raised
-
#
-
# @example Actual parameter does not contain expected entry supplied as key and value.
-
# object = mock()
-
# object.expects(:method_1).with(has_entry('key_1', 1))
-
# object.method_1('key_1' => 2, 'key_2' => 1)
-
# # error raised, because method_1 was not called with Hash containing entry: 'key_1' => 1
-
#
-
# @example Actual parameter does not contain expected entry supplied as +Hash+ entry.
-
#
-
# object = mock()
-
# object.expects(:method_1).with(has_entry('key_1' => 1))
-
# object.method_1('key_1' => 2, 'key_2' => 1)
-
# # error raised, because method_1 was not called with Hash containing entry: 'key_1' => 1
-
1
def has_entry(*options)
-
key, value = options.shift, options.shift
-
if key.is_a?(Hash)
-
case key.length
-
when 0
-
raise ArgumentError.new("Argument has no entries.")
-
when 1
-
key, value = key.to_a.flatten
-
else
-
raise ArgumentError.new("Argument has multiple entries. Use Mocha::ParameterMatchers#has_entries instead.")
-
end
-
end
-
HasEntry.new(key, value)
-
end
-
-
# Parameter matcher which matches when actual parameter contains expected +Hash+ entry.
-
1
class HasEntry < Base
-
-
# @private
-
1
def initialize(key, value)
-
@key, @value = key, value
-
end
-
-
# @private
-
1
def matches?(available_parameters)
-
parameter = available_parameters.shift
-
return false unless parameter.respond_to?(:keys) && parameter.respond_to?(:[])
-
matching_keys = parameter.keys.select { |key| @key.to_matcher.matches?([key]) }
-
matching_keys.any? { |key| @value.to_matcher.matches?([parameter[key]]) }
-
end
-
-
# @private
-
1
def mocha_inspect
-
"has_entry(#{@key.mocha_inspect} => #{@value.mocha_inspect})"
-
end
-
-
end
-
-
end
-
-
end
-
1
require 'mocha/parameter_matchers/base'
-
-
1
module Mocha
-
-
1
module ParameterMatchers
-
-
# Matches +Hash+ containing +key+.
-
#
-
# @param [Object] key expected key.
-
# @return [HasKey] parameter matcher.
-
#
-
# @see Expectation#with
-
#
-
# @example Actual parameter contains entry with expected key.
-
# object = mock()
-
# object.expects(:method_1).with(has_key('key_1'))
-
# object.method_1('key_1' => 1, 'key_2' => 2)
-
# # no error raised
-
#
-
# @example Actual parameter does not contain entry with expected key.
-
# object = mock()
-
# object.expects(:method_1).with(has_key('key_1'))
-
# object.method_1('key_2' => 2)
-
# # error raised, because method_1 was not called with Hash containing key: 'key_1'
-
1
def has_key(key)
-
HasKey.new(key)
-
end
-
-
# Parameter matcher which matches when actual parameter contains +Hash+ entry with expected key.
-
1
class HasKey < Base
-
-
# @private
-
1
def initialize(key)
-
@key = key
-
end
-
-
# @private
-
1
def matches?(available_parameters)
-
parameter = available_parameters.shift
-
return false unless parameter.respond_to?(:keys)
-
parameter.keys.any? { |key| @key.to_matcher.matches?([key]) }
-
end
-
-
# @private
-
1
def mocha_inspect
-
"has_key(#{@key.mocha_inspect})"
-
end
-
-
end
-
-
end
-
-
end
-
1
require 'mocha/parameter_matchers/base'
-
-
1
module Mocha
-
-
1
module ParameterMatchers
-
-
# Matches +Hash+ containing +value+.
-
#
-
# @param [Object] value expected value.
-
# @return [HasValue] parameter matcher.
-
#
-
# @see Expectation#with
-
#
-
# @example Actual parameter contains entry with expected value.
-
# object = mock()
-
# object.expects(:method_1).with(has_value(1))
-
# object.method_1('key_1' => 1, 'key_2' => 2)
-
# # no error raised
-
#
-
# @example Actual parameter does not contain entry with expected value.
-
# object = mock()
-
# object.expects(:method_1).with(has_value(1))
-
# object.method_1('key_2' => 2)
-
# # error raised, because method_1 was not called with Hash containing value: 1
-
1
def has_value(value)
-
HasValue.new(value)
-
end
-
-
# Parameter matcher which matches when actual parameter contains +Hash+ entry with expected value.
-
1
class HasValue < Base
-
-
# @private
-
1
def initialize(value)
-
@value = value
-
end
-
-
# @private
-
1
def matches?(available_parameters)
-
parameter = available_parameters.shift
-
return false unless parameter.respond_to?(:values)
-
parameter.values.any? { |value| @value.to_matcher.matches?([value]) }
-
end
-
-
# @private
-
1
def mocha_inspect
-
"has_value(#{@value.mocha_inspect})"
-
end
-
-
end
-
-
end
-
-
end
-
1
require 'mocha/parameter_matchers/base'
-
-
1
module Mocha
-
-
1
module ParameterMatchers
-
-
# Matches any object that responds with +true+ to +include?(item)+.
-
#
-
# @param [Object] item expected item.
-
# @return [Includes] parameter matcher.
-
#
-
# @see Expectation#with
-
#
-
# @example Actual parameter includes item.
-
# object = mock()
-
# object.expects(:method_1).with(includes('foo'))
-
# object.method_1(['foo', 'bar'])
-
# # no error raised
-
#
-
# @example Actual parameter does not include item.
-
# object.method_1(['baz'])
-
# # error raised, because ['baz'] does not include 'foo'.
-
1
def includes(item)
-
Includes.new(item)
-
end
-
-
# Parameter matcher which matches when actual parameter includes expected value.
-
1
class Includes < Base
-
-
# @private
-
1
def initialize(item)
-
@item = item
-
end
-
-
# @private
-
1
def matches?(available_parameters)
-
parameter = available_parameters.shift
-
return false unless parameter.respond_to?(:include?)
-
return parameter.include?(@item)
-
end
-
-
# @private
-
1
def mocha_inspect
-
"includes(#{@item.mocha_inspect})"
-
end
-
-
end
-
-
end
-
-
end
-
1
require 'mocha/parameter_matchers/base'
-
-
1
module Mocha
-
-
1
module ParameterMatchers
-
-
# Matches any object that is an instance of +klass+
-
#
-
# @param [Class] klass expected class.
-
# @return [InstanceOf] parameter matcher.
-
#
-
# @see Expectation#with
-
# @see Kernel#instance_of?
-
#
-
# @example Actual parameter is an instance of +String+.
-
# object = mock()
-
# object.expects(:method_1).with(instance_of(String))
-
# object.method_1('string')
-
# # no error raised
-
#
-
# @example Actual parameter is not an instance of +String+.
-
# object = mock()
-
# object.expects(:method_1).with(instance_of(String))
-
# object.method_1(99)
-
# # error raised, because method_1 was not called with an instance of String
-
1
def instance_of(klass)
-
InstanceOf.new(klass)
-
end
-
-
# Parameter matcher which matches when actual parameter is an instance of the specified class.
-
1
class InstanceOf < Base
-
-
# @private
-
1
def initialize(klass)
-
@klass = klass
-
end
-
-
# @private
-
1
def matches?(available_parameters)
-
parameter = available_parameters.shift
-
parameter.instance_of?(@klass)
-
end
-
-
# @private
-
1
def mocha_inspect
-
"instance_of(#{@klass.mocha_inspect})"
-
end
-
-
end
-
-
end
-
-
end
-
1
require 'mocha/parameter_matchers/base'
-
-
1
module Mocha
-
-
1
module ParameterMatchers
-
-
# Matches any object that is a +klass+.
-
#
-
# @param [Class] klass expected class.
-
# @return [IsA] parameter matcher.
-
#
-
# @see Expectation#with
-
# @see Kernel#is_a?
-
#
-
# @example Actual parameter is a +Integer+.
-
# object = mock()
-
# object.expects(:method_1).with(is_a(Integer))
-
# object.method_1(99)
-
# # no error raised
-
#
-
# @example Actual parameter is not a +Integer+.
-
# object = mock()
-
# object.expects(:method_1).with(is_a(Integer))
-
# object.method_1('string')
-
# # error raised, because method_1 was not called with an Integer
-
1
def is_a(klass)
-
IsA.new(klass)
-
end
-
-
# Parameter matcher which matches when actual parameter is a specific class.
-
1
class IsA < Base
-
-
# @private
-
1
def initialize(klass)
-
@klass = klass
-
end
-
-
# @private
-
1
def matches?(available_parameters)
-
parameter = available_parameters.shift
-
parameter.is_a?(@klass)
-
end
-
-
# @private
-
1
def mocha_inspect
-
"is_a(#{@klass.mocha_inspect})"
-
end
-
-
end
-
-
end
-
-
end
-
1
require 'mocha/parameter_matchers/base'
-
-
1
module Mocha
-
-
1
module ParameterMatchers
-
-
# Matches any +Object+ that is a kind of +klass+.
-
#
-
# @param [Class] klass expected class.
-
# @return [KindOf] parameter matcher.
-
#
-
# @see Expectation#with
-
# @see Kernel#kind_of?
-
#
-
# @example Actual parameter is a kind of +Integer+.
-
# object = mock()
-
# object.expects(:method_1).with(kind_of(Integer))
-
# object.method_1(99)
-
# # no error raised
-
#
-
# @example Actual parameter is not a kind of +Integer+.
-
# object = mock()
-
# object.expects(:method_1).with(kind_of(Integer))
-
# object.method_1('string')
-
# # error raised, because method_1 was not called with a kind of Integer
-
1
def kind_of(klass)
-
KindOf.new(klass)
-
end
-
-
# Parameter matcher which matches when actual parameter is a kind of specified class.
-
1
class KindOf < Base
-
-
# @private
-
1
def initialize(klass)
-
@klass = klass
-
end
-
-
# @private
-
1
def matches?(available_parameters)
-
parameter = available_parameters.shift
-
parameter.kind_of?(@klass)
-
end
-
-
# @private
-
1
def mocha_inspect
-
"kind_of(#{@klass.mocha_inspect})"
-
end
-
-
end
-
-
end
-
-
end
-
1
require 'mocha/parameter_matchers/base'
-
-
1
module Mocha
-
-
1
module ParameterMatchers
-
-
# Matches if +matcher+ does *not* match.
-
#
-
# @param [Base] matcher matcher whose logic to invert.
-
# @return [Not] parameter matcher.
-
#
-
# @see Expectation#with
-
#
-
# @example Actual parameter does not include the value +1+.
-
# object = mock()
-
# object.expects(:method_1).with(Not(includes(1)))
-
# object.method_1([0, 2, 3])
-
# # no error raised
-
#
-
# @example Actual parameter does include the value +1+.
-
# object = mock()
-
# object.expects(:method_1).with(Not(includes(1)))
-
# object.method_1([0, 1, 2, 3])
-
# # error raised, because method_1 was not called with object not including 1
-
1
def Not(matcher)
-
Not.new(matcher)
-
end
-
-
# Parameter matcher which inverts the logic of the specified matcher using a logical NOT operation.
-
1
class Not < Base
-
-
# @private
-
1
def initialize(matcher)
-
@matcher = matcher
-
end
-
-
# @private
-
1
def matches?(available_parameters)
-
parameter = available_parameters.shift
-
!@matcher.matches?([parameter])
-
end
-
-
# @private
-
1
def mocha_inspect
-
"Not(#{@matcher.mocha_inspect})"
-
end
-
-
end
-
-
end
-
-
end
-
1
require 'mocha/parameter_matchers/equals'
-
-
1
module Mocha
-
-
1
module ObjectMethods
-
# @private
-
1
def to_matcher
-
28
Mocha::ParameterMatchers::Equals.new(self)
-
end
-
end
-
-
end
-
-
# @private
-
1
class Object
-
1
include Mocha::ObjectMethods
-
end
-
1
module Mocha
-
-
1
module ParameterMatchers
-
-
# Matches optional parameters if available.
-
#
-
# @param [*Array<Base>] matchers matchers for optional parameters.
-
# @return [Optionally] parameter matcher.
-
#
-
# @see Expectation#with
-
#
-
# @example Only the two required parameters are supplied and they both match their expected value.
-
# object = mock()
-
# object.expects(:method_1).with(1, 2, optionally(3, 4))
-
# object.method_1(1, 2)
-
# # no error raised
-
#
-
# @example Both required parameters and one of the optional parameters are supplied and they all match their expected value.
-
# object = mock()
-
# object.expects(:method_1).with(1, 2, optionally(3, 4))
-
# object.method_1(1, 2, 3)
-
# # no error raised
-
#
-
# @example Both required parameters and both of the optional parameters are supplied and they all match their expected value.
-
# object = mock()
-
# object.expects(:method_1).with(1, 2, optionally(3, 4))
-
# object.method_1(1, 2, 3, 4)
-
# # no error raised
-
#
-
# @example One of the actual optional parameters does not match the expected value.
-
# object = mock()
-
# object.expects(:method_1).with(1, 2, optionally(3, 4))
-
# object.method_1(1, 2, 3, 5)
-
# # error raised, because optional parameters did not match
-
1
def optionally(*matchers)
-
Optionally.new(*matchers)
-
end
-
-
# Parameter matcher which allows optional parameters to be specified.
-
1
class Optionally < Base
-
-
# @private
-
1
def initialize(*parameters)
-
@matchers = parameters.map { |parameter| parameter.to_matcher }
-
end
-
-
# @private
-
1
def matches?(available_parameters)
-
index = 0
-
while (available_parameters.length > 0) && (index < @matchers.length) do
-
matcher = @matchers[index]
-
return false unless matcher.matches?(available_parameters)
-
index += 1
-
end
-
return true
-
end
-
-
# @private
-
1
def mocha_inspect
-
"optionally(#{@matchers.map { |matcher| matcher.mocha_inspect }.join(", ") })"
-
end
-
-
end
-
-
end
-
-
end
-
1
require 'mocha/parameter_matchers/base'
-
1
require 'uri'
-
-
1
module Mocha
-
1
module ParameterMatchers
-
-
# Matches a URI without regard to the ordering of parameters in the query string.
-
#
-
# @param [String] uri URI to match.
-
# @return [QueryStringMatches] parameter matcher.
-
#
-
# @see Expectation#with
-
#
-
# @example Actual URI has equivalent query string.
-
# object = mock()
-
# object.expects(:method_1).with(has_equivalent_query_string('http://example.com/foo?a=1&b=2))
-
# object.method_1('http://example.com/foo?b=2&a=1')
-
# # no error raised
-
#
-
# @example Actual URI does not have equivalent query string.
-
# object = mock()
-
# object.expects(:method_1).with(has_equivalent_query_string('http://example.com/foo?a=1&b=2))
-
# object.method_1('http://example.com/foo?a=1&b=3')
-
# # error raised, because the query parameters were different
-
1
def has_equivalent_query_string(uri)
-
QueryStringMatches.new(uri)
-
end
-
-
# Parameter matcher which matches URIs with equivalent query strings.
-
1
class QueryStringMatches < Base
-
-
# @private
-
1
def initialize(uri)
-
@uri = URI.parse(uri)
-
end
-
-
# @private
-
1
def matches?(available_parameters)
-
actual = explode(URI.parse(available_parameters.shift))
-
expected = explode(@uri)
-
actual == expected
-
end
-
-
# @private
-
1
def mocha_inspect
-
"has_equivalent_query_string(#{@uri.mocha_inspect})"
-
end
-
-
1
private
-
# @private
-
1
def explode(uri)
-
query_hash = (uri.query || '').split('&').inject({}){ |h, kv| h.merge(Hash[*kv.split('=')]) }
-
URI::Generic::COMPONENT.inject({}){ |h, k| h.merge(k => uri.__send__(k)) }.merge(:query => query_hash)
-
end
-
-
end
-
end
-
end
-
1
require 'mocha/parameter_matchers/base'
-
-
1
module Mocha
-
-
1
module ParameterMatchers
-
-
# Matches any object that matches +regexp+.
-
#
-
# @param [Regexp] regexp regular expression to match.
-
# @return [RegexpMatches] parameter matcher.
-
#
-
# @see Expectation#with
-
#
-
# @example Actual parameter is matched by specified regular expression.
-
# object = mock()
-
# object.expects(:method_1).with(regexp_matches(/e/))
-
# object.method_1('hello')
-
# # no error raised
-
#
-
# @example Actual parameter is not matched by specified regular expression.
-
# object = mock()
-
# object.expects(:method_1).with(regexp_matches(/a/))
-
# object.method_1('hello')
-
# # error raised, because method_1 was not called with a parameter that matched the
-
# # regular expression
-
1
def regexp_matches(regexp)
-
RegexpMatches.new(regexp)
-
end
-
-
# Parameter matcher which matches if specified regular expression matches actual paramter.
-
1
class RegexpMatches < Base
-
-
# @private
-
1
def initialize(regexp)
-
@regexp = regexp
-
end
-
-
# @private
-
1
def matches?(available_parameters)
-
parameter = available_parameters.shift
-
return false unless parameter.respond_to?(:=~)
-
parameter =~ @regexp
-
end
-
-
# @private
-
1
def mocha_inspect
-
"regexp_matches(#{@regexp.mocha_inspect})"
-
end
-
-
end
-
-
end
-
-
end
-
1
require 'mocha/parameter_matchers/base'
-
1
require 'yaml'
-
-
1
module Mocha
-
-
1
module ParameterMatchers
-
-
# Matches any object that responds to +message+ with +result+. To put it another way, it tests the quack, not the duck.
-
#
-
# @param [Symbol] message method to invoke.
-
# @param [Object] result expected result of sending +message+.
-
# @return [RespondsWith] parameter matcher.
-
#
-
# @see Expectation#with
-
#
-
# @example Actual parameter responds with "FOO" when :upcase is invoked.
-
# object = mock()
-
# object.expects(:method_1).with(responds_with(:upcase, "FOO"))
-
# object.method_1("foo")
-
# # no error raised, because "foo".upcase == "FOO"
-
#
-
# @example Actual parameter does not respond with "FOO" when :upcase is invoked.
-
# object = mock()
-
# object.expects(:method_1).with(responds_with(:upcase, "BAR"))
-
# object.method_1("foo")
-
# # error raised, because "foo".upcase != "BAR"
-
1
def responds_with(message, result)
-
RespondsWith.new(message, result)
-
end
-
-
# Parameter matcher which matches if actual parameter returns expected result when specified method is invoked.
-
1
class RespondsWith < Base
-
-
# @private
-
1
def initialize(message, result)
-
@message, @result = message, result
-
end
-
-
# @private
-
1
def matches?(available_parameters)
-
parameter = available_parameters.shift
-
parameter.__send__(@message) == @result
-
end
-
-
# @private
-
1
def mocha_inspect
-
"responds_with(#{@message.mocha_inspect}, #{@result.mocha_inspect})"
-
end
-
-
end
-
-
end
-
-
end
-
1
require 'mocha/parameter_matchers/base'
-
1
require 'yaml'
-
-
1
module Mocha
-
-
1
module ParameterMatchers
-
-
# Matches any YAML that represents the specified +object+
-
#
-
# @param [Object] object object whose YAML to compare.
-
# @return [YamlEquivalent] parameter matcher.
-
#
-
# @see Expectation#with
-
#
-
# @example Actual parameter is YAML equivalent of specified +object+.
-
# object = mock()
-
# object.expects(:method_1).with(yaml_equivalent(1, 2, 3))
-
# object.method_1("--- \n- 1\n- 2\n- 3\n")
-
# # no error raised
-
#
-
# @example Actual parameter is not YAML equivalent of specified +object+.
-
# object = mock()
-
# object.expects(:method_1).with(yaml_equivalent(1, 2, 3))
-
# object.method_1("--- \n- 1\n- 2\n")
-
# # error raised, because method_1 was not called with YAML representing the specified Array
-
1
def yaml_equivalent(object)
-
YamlEquivalent.new(object)
-
end
-
-
# Parameter matcher which matches if actual parameter is YAML equivalent of specified object.
-
1
class YamlEquivalent < Base
-
-
# @private
-
1
def initialize(object)
-
@object = object
-
end
-
-
# @private
-
1
def matches?(available_parameters)
-
parameter = available_parameters.shift
-
@object == YAML.load(parameter)
-
end
-
-
# @private
-
1
def mocha_inspect
-
"yaml_equivalent(#{@object.mocha_inspect})"
-
end
-
-
end
-
-
end
-
-
end
-
1
require 'mocha/inspect'
-
1
require 'mocha/parameter_matchers'
-
-
1
module Mocha
-
-
1
class ParametersMatcher
-
-
1
def initialize(expected_parameters = [ParameterMatchers::AnyParameters.new], &matching_block)
-
109
@expected_parameters, @matching_block = expected_parameters, matching_block
-
end
-
-
1
def match?(actual_parameters = [])
-
325
if @matching_block
-
return @matching_block.call(*actual_parameters)
-
else
-
325
return parameters_match?(actual_parameters)
-
end
-
end
-
-
1
def parameters_match?(actual_parameters)
-
667
matchers.all? { |matcher| matcher.matches?(actual_parameters) } && (actual_parameters.length == 0)
-
end
-
-
1
def mocha_inspect
-
signature = matchers.mocha_inspect
-
signature = signature.gsub(/^\[|\]$/, '')
-
signature = signature.gsub(/^\{|\}$/, '') if matchers.length == 1
-
"(#{signature})"
-
end
-
-
1
def matchers
-
667
@expected_parameters.map { |parameter| parameter.to_matcher }
-
end
-
-
end
-
-
end
-
1
require 'mocha/single_return_value'
-
-
1
module Mocha
-
-
1
class ReturnValues
-
-
1
def self.build(*values)
-
134
new(*values.map { |value| SingleReturnValue.new(value) })
-
end
-
-
1
attr_accessor :values
-
-
1
def initialize(*values)
-
234
@values = values
-
end
-
-
1
def next
-
283
case @values.length
-
when 0 then nil
-
265
when 1 then @values.first.evaluate
-
else @values.shift.evaluate
-
end
-
end
-
-
1
def +(other)
-
68
self.class.new(*(@values + other.values))
-
end
-
-
end
-
-
end
-
1
module Mocha
-
-
# Used to constrain the order in which expectations can occur.
-
#
-
# @see API#sequence
-
# @see Expectation#in_sequence
-
1
class Sequence
-
-
# @private
-
1
class InSequenceOrderingConstraint
-
-
1
def initialize(sequence, index)
-
@sequence, @index = sequence, index
-
end
-
-
1
def allows_invocation_now?
-
@sequence.satisfied_to_index?(@index)
-
end
-
-
1
def mocha_inspect
-
"in sequence #{@sequence.mocha_inspect}"
-
end
-
-
end
-
-
# @private
-
1
def initialize(name)
-
@name = name
-
@expectations = []
-
end
-
-
# @private
-
1
def constrain_as_next_in_sequence(expectation)
-
index = @expectations.length
-
@expectations << expectation
-
expectation.add_ordering_constraint(InSequenceOrderingConstraint.new(self, index))
-
end
-
-
# @private
-
1
def satisfied_to_index?(index)
-
@expectations[0...index].all? { |expectation| expectation.satisfied? }
-
end
-
-
# @private
-
1
def mocha_inspect
-
"#{@name.mocha_inspect}"
-
end
-
-
end
-
-
end
-
1
require 'mocha/is_a'
-
-
1
module Mocha
-
-
1
class SingleReturnValue
-
-
1
def initialize(value)
-
67
@value = value
-
end
-
-
1
def evaluate
-
264
@value
-
end
-
-
end
-
-
end
-
1
module Mocha
-
-
1
class SingleYield
-
-
1
attr_reader :parameters
-
-
1
def initialize(*parameters)
-
@parameters = parameters
-
end
-
-
1
def each
-
yield(@parameters)
-
end
-
-
end
-
-
end
-
-
1
module Mocha
-
-
# A state machine that is used to constrain the order of invocations.
-
# An invocation can be constrained to occur when a state {#is}, or {#is_not}, active.
-
1
class StateMachine
-
-
# Provides a mechanism to change the state of a {StateMachine} at some point in the future.
-
1
class State
-
-
# @private
-
1
def initialize(state_machine, state)
-
@state_machine, @state = state_machine, state
-
end
-
-
# @private
-
1
def activate
-
@state_machine.current_state = @state
-
end
-
-
# @private
-
1
def active?
-
@state_machine.current_state == @state
-
end
-
-
# @private
-
1
def mocha_inspect
-
"#{@state_machine.name} is #{@state.mocha_inspect}"
-
end
-
-
end
-
-
# Provides the ability to determine whether a {StateMachine} is in a specified state at some point in the future.
-
1
class StatePredicate
-
-
# @private
-
1
def initialize(state_machine, state)
-
@state_machine, @state = state_machine, state
-
end
-
-
# @private
-
1
def active?
-
@state_machine.current_state != @state
-
end
-
-
# @private
-
1
def mocha_inspect
-
"#{@state_machine.name} is not #{@state.mocha_inspect}"
-
end
-
-
end
-
-
# @private
-
1
attr_reader :name
-
-
# @private
-
1
attr_accessor :current_state
-
-
# @private
-
1
def initialize(name)
-
@name = name
-
@current_state = nil
-
end
-
-
# Put the {StateMachine} into the state specified by +initial_state_name+.
-
#
-
# @param [String] initial_state_name name of initial state
-
# @return [StateMachine] state machine, thereby allowing invocations of other {StateMachine} methods to be chained.
-
1
def starts_as(initial_state_name)
-
become(initial_state_name)
-
self
-
end
-
-
# Put the {StateMachine} into the +next_state_name+.
-
#
-
# @param [String] next_state_name name of new state
-
1
def become(next_state_name)
-
@current_state = next_state_name
-
end
-
-
# Provides a mechanism to change the {StateMachine} into the state specified by +state_name+ at some point in the future.
-
#
-
# Or provides a mechanism to determine whether the {StateMachine} is in the state specified by +state_name+ at some point in the future.
-
#
-
# @param [String] state_name name of new state
-
# @return [State] state which, when activated, will change the {StateMachine} into the state with the specified +state_name+.
-
1
def is(state_name)
-
State.new(self, state_name)
-
end
-
-
# Provides a mechanism to determine whether the {StateMachine} is not in the state specified by +state_name+ at some point in the future.
-
1
def is_not(state_name)
-
StatePredicate.new(self, state_name)
-
end
-
-
# @private
-
1
def mocha_inspect
-
if @current_state
-
"#{@name} is #{@current_state.mocha_inspect}"
-
else
-
"#{@name} has no current state"
-
end
-
end
-
-
end
-
-
end
-
1
require 'mocha/backtrace_filter'
-
-
1
module Mocha
-
-
# Exception raised when stubbing a particular method is not allowed.
-
#
-
# @see Configuration.prevent
-
1
class StubbingError < StandardError
-
-
# @private
-
1
def initialize(message = nil, backtrace = [])
-
super(message)
-
filter = BacktraceFilter.new
-
set_backtrace(filter.filtered(backtrace))
-
end
-
-
end
-
-
end
-
1
module Mocha
-
-
1
class Thrower
-
-
1
def initialize(tag, object = nil)
-
@tag, @object = tag, object
-
end
-
-
1
def evaluate
-
throw @tag, @object
-
end
-
-
end
-
-
end
-
1
module Mocha
-
-
# Exception raised when an unexpected method is invoked
-
1
class UnexpectedInvocation
-
-
# @private
-
1
def initialize(mock, symbol, *arguments)
-
@mock = mock
-
@method_matcher = MethodMatcher.new(symbol)
-
@parameters_matcher = ParametersMatcher.new(arguments)
-
end
-
-
# @private
-
1
def to_s
-
method_signature = "#{@mock.mocha_inspect}.#{@method_matcher.mocha_inspect}#{@parameters_matcher.mocha_inspect}"
-
"unexpected invocation: #{method_signature}\n"
-
end
-
-
end
-
-
end
-
1
require 'mocha/no_yields'
-
1
require 'mocha/single_yield'
-
1
require 'mocha/multiple_yields'
-
-
1
module Mocha
-
-
1
class YieldParameters
-
-
1
def initialize
-
98
@parameter_groups = []
-
end
-
-
1
def next_invocation
-
case @parameter_groups.length
-
when 0 then NoYields.new
-
when 1 then @parameter_groups.first
-
else @parameter_groups.shift
-
end
-
end
-
-
1
def add(*parameters)
-
@parameter_groups << SingleYield.new(*parameters)
-
end
-
-
1
def multiple_add(*parameter_groups)
-
@parameter_groups << MultipleYields.new(*parameter_groups)
-
end
-
-
end
-
-
end
-
#
-
# = base64.rb: methods for base64-encoding and -decoding strings
-
#
-
-
# The Base64 module provides for the encoding (#encode64, #strict_encode64,
-
# #urlsafe_encode64) and decoding (#decode64, #strict_decode64,
-
# #urlsafe_decode64) of binary data using a Base64 representation.
-
#
-
# == Example
-
#
-
# A simple encoding and decoding.
-
#
-
# require "base64"
-
#
-
# enc = Base64.encode64('Send reinforcements')
-
# # -> "U2VuZCByZWluZm9yY2VtZW50cw==\n"
-
# plain = Base64.decode64(enc)
-
# # -> "Send reinforcements"
-
#
-
# The purpose of using base64 to encode data is that it translates any
-
# binary data into purely printable characters.
-
-
1
module Base64
-
1
module_function
-
-
# Returns the Base64-encoded version of +bin+.
-
# This method complies with RFC 2045.
-
# Line feeds are added to every 60 encoded charactors.
-
#
-
# require 'base64'
-
# Base64.encode64("Now is the time for all good coders\nto learn Ruby")
-
#
-
# <i>Generates:</i>
-
#
-
# Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4g
-
# UnVieQ==
-
1
def encode64(bin)
-
[bin].pack("m")
-
end
-
-
# Returns the Base64-decoded version of +str+.
-
# This method complies with RFC 2045.
-
# Characters outside the base alphabet are ignored.
-
#
-
# require 'base64'
-
# str = 'VGhpcyBpcyBsaW5lIG9uZQpUaGlzIG' +
-
# 'lzIGxpbmUgdHdvClRoaXMgaXMgbGlu' +
-
# 'ZSB0aHJlZQpBbmQgc28gb24uLi4K'
-
# puts Base64.decode64(str)
-
#
-
# <i>Generates:</i>
-
#
-
# This is line one
-
# This is line two
-
# This is line three
-
# And so on...
-
1
def decode64(str)
-
35
str.unpack("m").first
-
end
-
-
# Returns the Base64-encoded version of +bin+.
-
# This method complies with RFC 4648.
-
# No line feeds are added.
-
1
def strict_encode64(bin)
-
33
[bin].pack("m0")
-
end
-
-
# Returns the Base64-decoded version of +str+.
-
# This method complies with RFC 4648.
-
# ArgumentError is raised if +str+ is incorrectly padded or contains
-
# non-alphabet characters. Note that CR or LF are also rejected.
-
1
def strict_decode64(str)
-
str.unpack("m0").first
-
end
-
-
# Returns the Base64-encoded version of +bin+.
-
# This method complies with ``Base 64 Encoding with URL and Filename Safe
-
# Alphabet'' in RFC 4648.
-
# The alphabet uses '-' instead of '+' and '_' instead of '/'.
-
1
def urlsafe_encode64(bin)
-
strict_encode64(bin).tr("+/", "-_")
-
end
-
-
# Returns the Base64-decoded version of +str+.
-
# This method complies with ``Base 64 Encoding with URL and Filename Safe
-
# Alphabet'' in RFC 4648.
-
# The alphabet uses '-' instead of '+' and '_' instead of '/'.
-
1
def urlsafe_decode64(str)
-
strict_decode64(str.tr("-_", "+/"))
-
end
-
end
-
#--
-
# benchmark.rb - a performance benchmarking library
-
#
-
# $Id: benchmark.rb 32269 2011-06-28 06:09:46Z naruse $
-
#
-
# Created by Gotoken (gotoken@notwork.org).
-
#
-
# Documentation by Gotoken (original RD), Lyle Johnson (RDoc conversion), and
-
# Gavin Sinclair (editing).
-
#++
-
#
-
# == Overview
-
#
-
# The Benchmark module provides methods for benchmarking Ruby code, giving
-
# detailed reports on the time taken for each task.
-
#
-
-
# The Benchmark module provides methods to measure and report the time
-
# used to execute Ruby code.
-
#
-
# * Measure the time to construct the string given by the expression
-
# <tt>"a"*1_000_000</tt>:
-
#
-
# require 'benchmark'
-
#
-
# puts Benchmark.measure { "a"*1_000_000 }
-
#
-
# On my machine (FreeBSD 3.2 on P5, 100MHz) this generates:
-
#
-
# 1.166667 0.050000 1.216667 ( 0.571355)
-
#
-
# This report shows the user CPU time, system CPU time, the sum of
-
# the user and system CPU times, and the elapsed real time. The unit
-
# of time is seconds.
-
#
-
# * Do some experiments sequentially using the #bm method:
-
#
-
# require 'benchmark'
-
#
-
# n = 50000
-
# Benchmark.bm do |x|
-
# x.report { for i in 1..n; a = "1"; end }
-
# x.report { n.times do ; a = "1"; end }
-
# x.report { 1.upto(n) do ; a = "1"; end }
-
# end
-
#
-
# The result:
-
#
-
# user system total real
-
# 1.033333 0.016667 1.016667 ( 0.492106)
-
# 1.483333 0.000000 1.483333 ( 0.694605)
-
# 1.516667 0.000000 1.516667 ( 0.711077)
-
#
-
# * Continuing the previous example, put a label in each report:
-
#
-
# require 'benchmark'
-
#
-
# n = 50000
-
# Benchmark.bm(7) do |x|
-
# x.report("for:") { for i in 1..n; a = "1"; end }
-
# x.report("times:") { n.times do ; a = "1"; end }
-
# x.report("upto:") { 1.upto(n) do ; a = "1"; end }
-
# end
-
#
-
# The result:
-
#
-
# user system total real
-
# for: 1.050000 0.000000 1.050000 ( 0.503462)
-
# times: 1.533333 0.016667 1.550000 ( 0.735473)
-
# upto: 1.500000 0.016667 1.516667 ( 0.711239)
-
#
-
#
-
# * The times for some benchmarks depend on the order in which items
-
# are run. These differences are due to the cost of memory
-
# allocation and garbage collection. To avoid these discrepancies,
-
# the #bmbm method is provided. For example, to compare ways to
-
# sort an array of floats:
-
#
-
# require 'benchmark'
-
#
-
# array = (1..1000000).map { rand }
-
#
-
# Benchmark.bmbm do |x|
-
# x.report("sort!") { array.dup.sort! }
-
# x.report("sort") { array.dup.sort }
-
# end
-
#
-
# The result:
-
#
-
# Rehearsal -----------------------------------------
-
# sort! 11.928000 0.010000 11.938000 ( 12.756000)
-
# sort 13.048000 0.020000 13.068000 ( 13.857000)
-
# ------------------------------- total: 25.006000sec
-
#
-
# user system total real
-
# sort! 12.959000 0.010000 12.969000 ( 13.793000)
-
# sort 12.007000 0.000000 12.007000 ( 12.791000)
-
#
-
#
-
# * Report statistics of sequential experiments with unique labels,
-
# using the #benchmark method:
-
#
-
# require 'benchmark'
-
# include Benchmark # we need the CAPTION and FORMAT constants
-
#
-
# n = 50000
-
# Benchmark.benchmark(CAPTION, 7, FORMAT, ">total:", ">avg:") do |x|
-
# tf = x.report("for:") { for i in 1..n; a = "1"; end }
-
# tt = x.report("times:") { n.times do ; a = "1"; end }
-
# tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end }
-
# [tf+tt+tu, (tf+tt+tu)/3]
-
# end
-
#
-
# The result:
-
#
-
# user system total real
-
# for: 1.016667 0.016667 1.033333 ( 0.485749)
-
# times: 1.450000 0.016667 1.466667 ( 0.681367)
-
# upto: 1.533333 0.000000 1.533333 ( 0.722166)
-
# >total: 4.000000 0.033333 4.033333 ( 1.889282)
-
# >avg: 1.333333 0.011111 1.344444 ( 0.629761)
-
-
1
module Benchmark
-
-
1
BENCHMARK_VERSION = "2002-04-25" #:nodoc"
-
-
# Invokes the block with a <tt>Benchmark::Report</tt> object, which
-
# may be used to collect and report on the results of individual
-
# benchmark tests. Reserves <i>label_width</i> leading spaces for
-
# labels on each line. Prints _caption_ at the top of the
-
# report, and uses _format_ to format each line.
-
# Returns an array of Benchmark::Tms objects.
-
#
-
# If the block returns an array of
-
# <tt>Benchmark::Tms</tt> objects, these will be used to format
-
# additional lines of output. If _label_ parameters are
-
# given, these are used to label these extra lines.
-
#
-
# _Note_: Other methods provide a simpler interface to this one, and are
-
# suitable for nearly all benchmarking requirements. See the examples in
-
# Benchmark, and the #bm and #bmbm methods.
-
#
-
# Example:
-
#
-
# require 'benchmark'
-
# include Benchmark # we need the CAPTION and FORMAT constants
-
#
-
# n = 50000
-
# Benchmark.benchmark(CAPTION, 7, FORMAT, ">total:", ">avg:") do |x|
-
# tf = x.report("for:") { for i in 1..n; a = "1"; end }
-
# tt = x.report("times:") { n.times do ; a = "1"; end }
-
# tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end }
-
# [tf+tt+tu, (tf+tt+tu)/3]
-
# end
-
#
-
# <i>Generates:</i>
-
#
-
# user system total real
-
# for: 1.016667 0.016667 1.033333 ( 0.485749)
-
# times: 1.450000 0.016667 1.466667 ( 0.681367)
-
# upto: 1.533333 0.000000 1.533333 ( 0.722166)
-
# >total: 4.000000 0.033333 4.033333 ( 1.889282)
-
# >avg: 1.333333 0.011111 1.344444 ( 0.629761)
-
#
-
-
1
def benchmark(caption = "", label_width = nil, format = nil, *labels) # :yield: report
-
sync = STDOUT.sync
-
STDOUT.sync = true
-
label_width ||= 0
-
label_width += 1
-
format ||= FORMAT
-
print ' '*label_width + caption
-
report = Report.new(label_width, format)
-
results = yield(report)
-
Array === results and results.grep(Tms).each {|t|
-
print((labels.shift || t.label || "").ljust(label_width), t.format(format))
-
}
-
report.list
-
ensure
-
STDOUT.sync = sync unless sync.nil?
-
end
-
-
-
# A simple interface to the #benchmark method, #bm is generates sequential reports
-
# with labels. The parameters have the same meaning as for #benchmark.
-
#
-
# require 'benchmark'
-
#
-
# n = 50000
-
# Benchmark.bm(7) do |x|
-
# x.report("for:") { for i in 1..n; a = "1"; end }
-
# x.report("times:") { n.times do ; a = "1"; end }
-
# x.report("upto:") { 1.upto(n) do ; a = "1"; end }
-
# end
-
#
-
# <i>Generates:</i>
-
#
-
# user system total real
-
# for: 1.050000 0.000000 1.050000 ( 0.503462)
-
# times: 1.533333 0.016667 1.550000 ( 0.735473)
-
# upto: 1.500000 0.016667 1.516667 ( 0.711239)
-
#
-
-
1
def bm(label_width = 0, *labels, &blk) # :yield: report
-
benchmark(CAPTION, label_width, FORMAT, *labels, &blk)
-
end
-
-
-
# Sometimes benchmark results are skewed because code executed
-
# earlier encounters different garbage collection overheads than
-
# that run later. #bmbm attempts to minimize this effect by running
-
# the tests twice, the first time as a rehearsal in order to get the
-
# runtime environment stable, the second time for
-
# real. <tt>GC.start</tt> is executed before the start of each of
-
# the real timings; the cost of this is not included in the
-
# timings. In reality, though, there's only so much that #bmbm can
-
# do, and the results are not guaranteed to be isolated from garbage
-
# collection and other effects.
-
#
-
# Because #bmbm takes two passes through the tests, it can
-
# calculate the required label width.
-
#
-
# require 'benchmark'
-
#
-
# array = (1..1000000).map { rand }
-
#
-
# Benchmark.bmbm do |x|
-
# x.report("sort!") { array.dup.sort! }
-
# x.report("sort") { array.dup.sort }
-
# end
-
#
-
# <i>Generates:</i>
-
#
-
# Rehearsal -----------------------------------------
-
# sort! 11.928000 0.010000 11.938000 ( 12.756000)
-
# sort 13.048000 0.020000 13.068000 ( 13.857000)
-
# ------------------------------- total: 25.006000sec
-
#
-
# user system total real
-
# sort! 12.959000 0.010000 12.969000 ( 13.793000)
-
# sort 12.007000 0.000000 12.007000 ( 12.791000)
-
#
-
# #bmbm yields a Benchmark::Job object and returns an array of
-
# Benchmark::Tms objects.
-
#
-
1
def bmbm(width = 0, &blk) # :yield: job
-
job = Job.new(width)
-
yield(job)
-
width = job.width + 1
-
sync = STDOUT.sync
-
STDOUT.sync = true
-
-
# rehearsal
-
puts 'Rehearsal '.ljust(width+CAPTION.length,'-')
-
ets = job.list.inject(Tms.new) { |sum,(label,item)|
-
print label.ljust(width)
-
res = Benchmark.measure(&item)
-
print res.format
-
sum + res
-
}.format("total: %tsec")
-
print " #{ets}\n\n".rjust(width+CAPTION.length+2,'-')
-
-
# take
-
print ' '*width + CAPTION
-
job.list.map { |label,item|
-
GC.start
-
print label.ljust(width)
-
Benchmark.measure(label, &item).tap { |res| print res }
-
}
-
ensure
-
STDOUT.sync = sync unless sync.nil?
-
end
-
-
#
-
# Returns the time used to execute the given block as a
-
# Benchmark::Tms object.
-
#
-
1
def measure(label = "") # :yield:
-
t0, r0 = Process.times, Time.now
-
yield
-
t1, r1 = Process.times, Time.now
-
Benchmark::Tms.new(t1.utime - t0.utime,
-
t1.stime - t0.stime,
-
t1.cutime - t0.cutime,
-
t1.cstime - t0.cstime,
-
r1.to_f - r0.to_f,
-
label)
-
end
-
-
#
-
# Returns the elapsed real time used to execute the given block.
-
#
-
1
def realtime # :yield:
-
5
r0 = Time.now
-
5
yield
-
4
Time.now - r0
-
end
-
-
1
module_function :benchmark, :measure, :realtime, :bm, :bmbm
-
-
#
-
# A Job is a sequence of labelled blocks to be processed by the
-
# Benchmark.bmbm method. It is of little direct interest to the user.
-
#
-
1
class Job # :nodoc:
-
#
-
# Returns an initialized Job instance.
-
# Usually, one doesn't call this method directly, as new
-
# Job objects are created by the #bmbm method.
-
# _width_ is a initial value for the label offset used in formatting;
-
# the #bmbm method passes its _width_ argument to this constructor.
-
#
-
1
def initialize(width)
-
@width = width
-
@list = []
-
end
-
-
#
-
# Registers the given label and block pair in the job list.
-
#
-
1
def item(label = "", &blk) # :yield:
-
raise ArgumentError, "no block" unless block_given?
-
label = label.to_s
-
w = label.length
-
@width = w if @width < w
-
@list << [label, blk]
-
self
-
end
-
-
1
alias report item
-
-
# An array of 2-element arrays, consisting of label and block pairs.
-
1
attr_reader :list
-
-
# Length of the widest label in the #list.
-
1
attr_reader :width
-
end
-
-
#
-
# This class is used by the Benchmark.benchmark and Benchmark.bm methods.
-
# It is of little direct interest to the user.
-
#
-
1
class Report # :nodoc:
-
#
-
# Returns an initialized Report instance.
-
# Usually, one doesn't call this method directly, as new
-
# Report objects are created by the #benchmark and #bm methods.
-
# _width_ and _format_ are the label offset and
-
# format string used by Tms#format.
-
#
-
1
def initialize(width = 0, format = nil)
-
@width, @format, @list = width, format, []
-
end
-
-
#
-
# Prints the _label_ and measured time for the block,
-
# formatted by _format_. See Tms#format for the
-
# formatting rules.
-
#
-
1
def item(label = "", *format, &blk) # :yield:
-
print label.to_s.ljust(@width)
-
@list << res = Benchmark.measure(label, &blk)
-
print res.format(@format, *format)
-
res
-
end
-
-
1
alias report item
-
-
# An array of Benchmark::Tms objects representing each item.
-
1
attr_reader :list
-
end
-
-
-
-
#
-
# A data object, representing the times associated with a benchmark
-
# measurement.
-
#
-
1
class Tms
-
-
# Default caption, see also Benchmark::CAPTION
-
1
CAPTION = " user system total real\n"
-
-
# Default format string, see also Benchmark::FORMAT
-
1
FORMAT = "%10.6u %10.6y %10.6t %10.6r\n"
-
-
# User CPU time
-
1
attr_reader :utime
-
-
# System CPU time
-
1
attr_reader :stime
-
-
# User CPU time of children
-
1
attr_reader :cutime
-
-
# System CPU time of children
-
1
attr_reader :cstime
-
-
# Elapsed real time
-
1
attr_reader :real
-
-
# Total time, that is _utime_ + _stime_ + _cutime_ + _cstime_
-
1
attr_reader :total
-
-
# Label
-
1
attr_reader :label
-
-
#
-
# Returns an initialized Tms object which has
-
# _utime_ as the user CPU time, _stime_ as the system CPU time,
-
# _cutime_ as the children's user CPU time, _cstime_ as the children's
-
# system CPU time, _real_ as the elapsed real time and _label_ as the label.
-
#
-
1
def initialize(utime = 0.0, stime = 0.0, cutime = 0.0, cstime = 0.0, real = 0.0, label = nil)
-
@utime, @stime, @cutime, @cstime, @real, @label = utime, stime, cutime, cstime, real, label.to_s
-
@total = @utime + @stime + @cutime + @cstime
-
end
-
-
#
-
# Returns a new Tms object whose times are the sum of the times for this
-
# Tms object, plus the time required to execute the code block (_blk_).
-
#
-
1
def add(&blk) # :yield:
-
self + Benchmark.measure(&blk)
-
end
-
-
#
-
# An in-place version of #add.
-
#
-
1
def add!(&blk)
-
t = Benchmark.measure(&blk)
-
@utime = utime + t.utime
-
@stime = stime + t.stime
-
@cutime = cutime + t.cutime
-
@cstime = cstime + t.cstime
-
@real = real + t.real
-
self
-
end
-
-
#
-
# Returns a new Tms object obtained by memberwise summation
-
# of the individual times for this Tms object with those of the other
-
# Tms object.
-
# This method and #/() are useful for taking statistics.
-
#
-
1
def +(other); memberwise(:+, other) end
-
-
#
-
# Returns a new Tms object obtained by memberwise subtraction
-
# of the individual times for the other Tms object from those of this
-
# Tms object.
-
#
-
1
def -(other); memberwise(:-, other) end
-
-
#
-
# Returns a new Tms object obtained by memberwise multiplication
-
# of the individual times for this Tms object by _x_.
-
#
-
1
def *(x); memberwise(:*, x) end
-
-
#
-
# Returns a new Tms object obtained by memberwise division
-
# of the individual times for this Tms object by _x_.
-
# This method and #+() are useful for taking statistics.
-
#
-
1
def /(x); memberwise(:/, x) end
-
-
#
-
# Returns the contents of this Tms object as
-
# a formatted string, according to a format string
-
# like that passed to Kernel.format. In addition, #format
-
# accepts the following extensions:
-
#
-
# <tt>%u</tt>:: Replaced by the user CPU time, as reported by Tms#utime.
-
# <tt>%y</tt>:: Replaced by the system CPU time, as reported by #stime (Mnemonic: y of "s*y*stem")
-
# <tt>%U</tt>:: Replaced by the children's user CPU time, as reported by Tms#cutime
-
# <tt>%Y</tt>:: Replaced by the children's system CPU time, as reported by Tms#cstime
-
# <tt>%t</tt>:: Replaced by the total CPU time, as reported by Tms#total
-
# <tt>%r</tt>:: Replaced by the elapsed real time, as reported by Tms#real
-
# <tt>%n</tt>:: Replaced by the label string, as reported by Tms#label (Mnemonic: n of "*n*ame")
-
#
-
# If _format_ is not given, FORMAT is used as default value, detailing the
-
# user, system and real elapsed time.
-
#
-
1
def format(format = nil, *args)
-
str = (format || FORMAT).dup
-
str.gsub!(/(%[-+\.\d]*)n/) { "#{$1}s" % label }
-
str.gsub!(/(%[-+\.\d]*)u/) { "#{$1}f" % utime }
-
str.gsub!(/(%[-+\.\d]*)y/) { "#{$1}f" % stime }
-
str.gsub!(/(%[-+\.\d]*)U/) { "#{$1}f" % cutime }
-
str.gsub!(/(%[-+\.\d]*)Y/) { "#{$1}f" % cstime }
-
str.gsub!(/(%[-+\.\d]*)t/) { "#{$1}f" % total }
-
str.gsub!(/(%[-+\.\d]*)r/) { "(#{$1}f)" % real }
-
format ? str % args : str
-
end
-
-
#
-
# Same as #format.
-
#
-
1
def to_s
-
format
-
end
-
-
#
-
# Returns a new 6-element array, consisting of the
-
# label, user CPU time, system CPU time, children's
-
# user CPU time, children's system CPU time and elapsed
-
# real time.
-
#
-
1
def to_a
-
[@label, @utime, @stime, @cutime, @cstime, @real]
-
end
-
-
1
protected
-
-
#
-
# Returns a new Tms object obtained by memberwise operation +op+
-
# of the individual times for this Tms object with those of the other
-
# Tms object.
-
#
-
# +op+ can be a mathematical operation such as <tt>+</tt>, <tt>-</tt>,
-
# <tt>*</tt>, <tt>/</tt>
-
#
-
1
def memberwise(op, x)
-
case x
-
when Benchmark::Tms
-
Benchmark::Tms.new(utime.__send__(op, x.utime),
-
stime.__send__(op, x.stime),
-
cutime.__send__(op, x.cutime),
-
cstime.__send__(op, x.cstime),
-
real.__send__(op, x.real)
-
)
-
else
-
Benchmark::Tms.new(utime.__send__(op, x),
-
stime.__send__(op, x),
-
cutime.__send__(op, x),
-
cstime.__send__(op, x),
-
real.__send__(op, x)
-
)
-
end
-
end
-
end
-
-
# The default caption string (heading above the output times).
-
1
CAPTION = Benchmark::Tms::CAPTION
-
-
# The default format string used to display times. See also Benchmark::Tms#format.
-
1
FORMAT = Benchmark::Tms::FORMAT
-
end
-
-
1
if __FILE__ == $0
-
include Benchmark
-
-
n = ARGV[0].to_i.nonzero? || 50000
-
puts %Q([#{n} times iterations of `a = "1"'])
-
benchmark(" " + CAPTION, 7, FORMAT) do |x|
-
x.report("for:") {for _ in 1..n; _ = "1"; end} # Benchmark.measure
-
x.report("times:") {n.times do ; _ = "1"; end}
-
x.report("upto:") {1.upto(n) do ; _ = "1"; end}
-
end
-
-
benchmark do
-
[
-
measure{for _ in 1..n; _ = "1"; end}, # Benchmark.measure
-
measure{n.times do ; _ = "1"; end},
-
measure{1.upto(n) do ; _ = "1"; end}
-
]
-
end
-
end
-
1
class Integer < Numeric
-
# call-seq:
-
# int.to_d -> bigdecimal
-
#
-
# Convert +int+ to a BigDecimal and return it.
-
#
-
# require 'bigdecimal'
-
# require 'bigdecimal/util'
-
#
-
# 42.to_d
-
# # => #<BigDecimal:1008ef070,'0.42E2',9(36)>
-
#
-
1
def to_d
-
BigDecimal(self)
-
end
-
end
-
-
1
class Float < Numeric
-
# call-seq:
-
# flt.to_d(precision=nil) -> bigdecimal
-
#
-
# Convert +flt+ to a BigDecimal and return it.
-
#
-
# require 'bigdecimal'
-
# require 'bigdecimal/util'
-
#
-
# 0.5.to_d
-
# # => #<BigDecimal:1dc69e0,'0.5E0',9(18)>
-
#
-
1
def to_d(precision=nil)
-
BigDecimal(self, precision || Float::DIG+1)
-
end
-
end
-
-
1
class String
-
# call-seq:
-
# string.to_d -> bigdecimal
-
#
-
# Convert +string+ to a BigDecimal and return it.
-
#
-
# require 'bigdecimal'
-
# require 'bigdecimal/util'
-
#
-
# "0.5".to_d
-
# # => #<BigDecimal:1dc69e0,'0.5E0',9(18)>
-
#
-
1
def to_d
-
BigDecimal(self)
-
end
-
end
-
-
1
class BigDecimal < Numeric
-
# call-seq:
-
# a.to_digits -> string
-
#
-
# Converts a BigDecimal to a String of the form "nnnnnn.mmm".
-
# This method is deprecated; use BigDecimal#to_s("F") instead.
-
#
-
# require 'bigdecimal'
-
# require 'bigdecimal/util'
-
#
-
# d = BigDecimal.new("3.14")
-
# d.to_digits
-
# # => "3.14"
-
1
def to_digits
-
if self.nan? || self.infinite? || self.zero?
-
self.to_s
-
else
-
i = self.to_i.to_s
-
_,f,_,z = self.frac.split
-
i + "." + ("0"*(-z)) + f
-
end
-
end
-
-
# call-seq:
-
# a.to_d -> bigdecimal
-
#
-
# Returns self.
-
1
def to_d
-
1
self
-
end
-
end
-
-
1
class Rational < Numeric
-
# call-seq:
-
# r.to_d(sig) -> bigdecimal
-
#
-
# Converts a Rational to a BigDecimal. Takes an optional parameter +sig+ to
-
# limit the amount of significant digits.
-
# If a negative precision is given, raise ArgumentError.
-
# The zero precision and implicit precision is deprecated.
-
#
-
# r = (22/7.0).to_r
-
# # => (7077085128725065/2251799813685248)
-
# r.to_d
-
# # => #<BigDecimal:1a52bd8,'0.3142857142 8571427937 0154144999 105E1',45(63)>
-
# r.to_d(3)
-
# # => #<BigDecimal:1a44d08,'0.314E1',18(36)>
-
1
def to_d(precision=0)
-
if precision < 0
-
raise ArgumentError, "negative precision"
-
elsif precision == 0
-
warn "zero and implicit precision is deprecated."
-
precision = BigDecimal.double_fig*2+1
-
end
-
num = self.numerator
-
BigDecimal(num).div(self.denominator, precision)
-
end
-
end
-
# = delegate -- Support for the Delegation Pattern
-
#
-
# Documentation by James Edward Gray II and Gavin Sinclair
-
-
##
-
# This library provides three different ways to delegate method calls to an
-
# object. The easiest to use is SimpleDelegator. Pass an object to the
-
# constructor and all methods supported by the object will be delegated. This
-
# object can be changed later.
-
#
-
# Going a step further, the top level DelegateClass method allows you to easily
-
# setup delegation through class inheritance. This is considerably more
-
# flexible and thus probably the most common use for this library.
-
#
-
# Finally, if you need full control over the delegation scheme, you can inherit
-
# from the abstract class Delegator and customize as needed. (If you find
-
# yourself needing this control, have a look at Forwardable which is also in
-
# the standard library. It may suit your needs better.)
-
#
-
# SimpleDelegator's implementation serves as a nice example if the use of
-
# Delegator:
-
#
-
# class SimpleDelegator < Delegator
-
# def initialize(obj)
-
# super # pass obj to Delegator constructor, required
-
# @delegate_sd_obj = obj # store obj for future use
-
# end
-
#
-
# def __getobj__
-
# @delegate_sd_obj # return object we are delegating to, required
-
# end
-
#
-
# def __setobj__(obj)
-
# @delegate_sd_obj = obj # change delegation object,
-
# # a feature we're providing
-
# end
-
# end
-
#
-
# == Notes
-
#
-
# Be advised, RDoc will not detect delegated methods.
-
#
-
1
class Delegator < BasicObject
-
1
kernel = ::Kernel.dup
-
1
kernel.class_eval do
-
1
[:to_s,:inspect,:=~,:!~,:===,:<=>,:eql?,:hash].each do |m|
-
8
undef_method m
-
end
-
end
-
1
include kernel
-
-
# :stopdoc:
-
1
def self.const_missing(n)
-
519
::Object.const_get(n)
-
end
-
# :startdoc:
-
-
#
-
# Pass in the _obj_ to delegate method calls to. All methods supported by
-
# _obj_ will be delegated to.
-
#
-
1
def initialize(obj)
-
71
__setobj__(obj)
-
end
-
-
#
-
# Handles the magic of delegation through \_\_getobj\_\_.
-
#
-
1
def method_missing(m, *args, &block)
-
target = self.__getobj__
-
begin
-
target.respond_to?(m) ? target.__send__(m, *args, &block) : super(m, *args, &block)
-
ensure
-
$@.delete_if {|t| %r"\A#{Regexp.quote(__FILE__)}:#{__LINE__-2}:"o =~ t} if $@
-
end
-
end
-
-
#
-
# Checks for a method provided by this the delegate object by forwarding the
-
# call through \_\_getobj\_\_.
-
#
-
1
def respond_to_missing?(m, include_private)
-
r = self.__getobj__.respond_to?(m, include_private)
-
if r && include_private && !self.__getobj__.respond_to?(m, false)
-
warn "#{caller(3)[0]}: delegator does not forward private method \##{m}"
-
return false
-
end
-
r
-
end
-
-
#
-
# Returns the methods available to this delegate object as the union
-
# of this object's and \_\_getobj\_\_ methods.
-
#
-
1
def methods
-
__getobj__.methods | super
-
end
-
-
#
-
# Returns the methods available to this delegate object as the union
-
# of this object's and \_\_getobj\_\_ public methods.
-
#
-
1
def public_methods(all=true)
-
__getobj__.public_methods(all) | super
-
end
-
-
#
-
# Returns the methods available to this delegate object as the union
-
# of this object's and \_\_getobj\_\_ protected methods.
-
#
-
1
def protected_methods(all=true)
-
__getobj__.protected_methods(all) | super
-
end
-
-
# Note: no need to specialize private_methods, since they are not forwarded
-
-
#
-
# Returns true if two objects are considered of equal value.
-
#
-
1
def ==(obj)
-
return true if obj.equal?(self)
-
self.__getobj__ == obj
-
end
-
-
#
-
# Returns true if two objects are not considered of equal value.
-
#
-
1
def !=(obj)
-
return false if obj.equal?(self)
-
__getobj__ != obj
-
end
-
-
1
def !
-
!__getobj__
-
end
-
-
#
-
# This method must be overridden by subclasses and should return the object
-
# method calls are being delegated to.
-
#
-
1
def __getobj__
-
raise NotImplementedError, "need to define `__getobj__'"
-
end
-
-
#
-
# This method must be overridden by subclasses and change the object delegate
-
# to _obj_.
-
#
-
1
def __setobj__(obj)
-
raise NotImplementedError, "need to define `__setobj__'"
-
end
-
-
#
-
# Serialization support for the object returned by \_\_getobj\_\_.
-
#
-
1
def marshal_dump
-
ivars = instance_variables.reject {|var| /\A@delegate_/ =~ var}
-
[
-
:__v2__,
-
ivars, ivars.map{|var| instance_variable_get(var)},
-
__getobj__
-
]
-
end
-
-
#
-
# Reinitializes delegation from a serialized object.
-
#
-
1
def marshal_load(data)
-
version, vars, values, obj = data
-
if version == :__v2__
-
vars.each_with_index{|var, i| instance_variable_set(var, values[i])}
-
__setobj__(obj)
-
else
-
__setobj__(data)
-
end
-
end
-
-
1
def initialize_clone(obj) # :nodoc:
-
self.__setobj__(obj.__getobj__.clone)
-
end
-
1
def initialize_dup(obj) # :nodoc:
-
self.__setobj__(obj.__getobj__.dup)
-
end
-
1
private :initialize_clone, :initialize_dup
-
-
##
-
# :method: trust
-
# Trust both the object returned by \_\_getobj\_\_ and self.
-
#
-
-
##
-
# :method: untrust
-
# Untrust both the object returned by \_\_getobj\_\_ and self.
-
#
-
-
##
-
# :method: taint
-
# Taint both the object returned by \_\_getobj\_\_ and self.
-
#
-
-
##
-
# :method: untaint
-
# Untaint both the object returned by \_\_getobj\_\_ and self.
-
#
-
-
##
-
# :method: freeze
-
# Freeze both the object returned by \_\_getobj\_\_ and self.
-
#
-
-
1
[:trust, :untrust, :taint, :untaint, :freeze].each do |method|
-
5
define_method method do
-
__getobj__.send(method)
-
super()
-
end
-
end
-
-
1
@delegator_api = self.public_instance_methods
-
1
def self.public_api # :nodoc:
-
1
@delegator_api
-
end
-
end
-
-
##
-
# A concrete implementation of Delegator, this class provides the means to
-
# delegate all supported method calls to the object passed into the constructor
-
# and even to change the object being delegated to at a later time with
-
# #__setobj__.
-
#
-
# Here's a simple example that takes advantage of the fact that
-
# SimpleDelegator's delegation object can be changed at any time.
-
#
-
# class Stats
-
# def initialize
-
# @source = SimpleDelegator.new([])
-
# end
-
#
-
# def stats(records)
-
# @source.__setobj__(records)
-
#
-
# "Elements: #{@source.size}\n" +
-
# " Non-Nil: #{@source.compact.size}\n" +
-
# " Unique: #{@source.uniq.size}\n"
-
# end
-
# end
-
#
-
# s = Stats.new
-
# puts s.stats(%w{James Edward Gray II})
-
# puts
-
# puts s.stats([1, 2, 3, nil, 4, 5, 1, 2])
-
#
-
# Prints:
-
#
-
# Elements: 4
-
# Non-Nil: 4
-
# Unique: 4
-
#
-
# Elements: 8
-
# Non-Nil: 7
-
# Unique: 6
-
#
-
1
class SimpleDelegator<Delegator
-
# Returns the current object method calls are being delegated to.
-
1
def __getobj__
-
@delegate_sd_obj
-
end
-
-
#
-
# Changes the delegate object to _obj_.
-
#
-
# It's important to note that this does *not* cause SimpleDelegator's methods
-
# to change. Because of this, you probably only want to change delegation
-
# to objects of the same type as the original delegate.
-
#
-
# Here's an example of changing the delegation object.
-
#
-
# names = SimpleDelegator.new(%w{James Edward Gray II})
-
# puts names[1] # => Edward
-
# names.__setobj__(%w{Gavin Sinclair})
-
# puts names[1] # => Sinclair
-
#
-
1
def __setobj__(obj)
-
raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
-
@delegate_sd_obj = obj
-
end
-
end
-
-
# :stopdoc:
-
1
def Delegator.delegating_block(mid)
-
136
lambda do |*args, &block|
-
202
target = self.__getobj__
-
202
begin
-
202
target.__send__(mid, *args, &block)
-
ensure
-
202
$@.delete_if {|t| /\A#{Regexp.quote(__FILE__)}:#{__LINE__-2}:/o =~ t} if $@
-
end
-
end
-
end
-
# :startdoc:
-
-
#
-
# The primary interface to this library. Use to setup delegation when defining
-
# your class.
-
#
-
# class MyClass < DelegateClass(ClassToDelegateTo) # Step 1
-
# def initialize
-
# super(obj_of_ClassToDelegateTo) # Step 2
-
# end
-
# end
-
#
-
# Here's a sample of use from Tempfile which is really a File object with a
-
# few special rules about storage location and when the File should be
-
# deleted. That makes for an almost textbook perfect example of how to use
-
# delegation.
-
#
-
# class Tempfile < DelegateClass(File)
-
# # constant and class member data initialization...
-
#
-
# def initialize(basename, tmpdir=Dir::tmpdir)
-
# # build up file path/name in var tmpname...
-
#
-
# @tmpfile = File.open(tmpname, File::RDWR|File::CREAT|File::EXCL, 0600)
-
#
-
# # ...
-
#
-
# super(@tmpfile)
-
#
-
# # below this point, all methods of File are supported...
-
# end
-
#
-
# # ...
-
# end
-
#
-
1
def DelegateClass(superclass)
-
1
klass = Class.new(Delegator)
-
1
methods = superclass.instance_methods
-
1
methods -= ::Delegator.public_api
-
1
methods -= [:to_s,:inspect,:=~,:!~,:===]
-
1
klass.module_eval do
-
1
def __getobj__ # :nodoc:
-
202
@delegate_dc_obj
-
end
-
1
def __setobj__(obj) # :nodoc:
-
71
raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
-
71
@delegate_dc_obj = obj
-
end
-
1
methods.each do |method|
-
136
define_method(method, Delegator.delegating_block(method))
-
end
-
end
-
1
klass.define_singleton_method :public_instance_methods do |all=true|
-
super(all) - superclass.protected_instance_methods
-
end
-
1
klass.define_singleton_method :protected_instance_methods do |all=true|
-
super(all) | superclass.protected_instance_methods
-
end
-
1
return klass
-
end
-
-
# :enddoc:
-
-
1
if __FILE__ == $0
-
class ExtArray<DelegateClass(Array)
-
def initialize()
-
super([])
-
end
-
end
-
-
ary = ExtArray.new
-
p ary.class
-
ary.push 25
-
p ary
-
ary.push 42
-
ary.each {|x| p x}
-
-
foo = Object.new
-
def foo.test
-
25
-
end
-
def foo.iter
-
yield self
-
end
-
def foo.error
-
raise 'this is OK'
-
end
-
foo2 = SimpleDelegator.new(foo)
-
p foo2
-
foo2.instance_eval{print "foo\n"}
-
p foo.test == foo2.test # => true
-
p foo2.iter{[55,true]} # => true
-
foo2.error # raise error!
-
end
-
# logger.rb - simple logging utility
-
# Copyright (C) 2000-2003, 2005, 2008, 2011 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
-
#
-
# Documentation:: NAKAMURA, Hiroshi and Gavin Sinclair
-
# License::
-
# You can redistribute it and/or modify it under the same terms of Ruby's
-
# license; either the dual license version in 2003, or any later version.
-
# Revision:: $Id: logger.rb 31641 2011-05-19 00:07:25Z nobu $
-
#
-
# A simple system for logging messages. See Logger for more documentation.
-
-
1
require 'monitor'
-
-
# == Description
-
#
-
# The Logger class provides a simple but sophisticated logging utility that
-
# you can use to output messages.
-
#
-
# The messages have associated levels, such as +INFO+ or +ERROR+ that indicate
-
# their importance. You can then give the Logger a level, and only messages
-
# at that level of higher will be printed.
-
#
-
# The levels are:
-
#
-
# +FATAL+:: an unhandleable error that results in a program crash
-
# +ERROR+:: a handleable error condition
-
# +WARN+:: a warning
-
# +INFO+:: generic (useful) information about system operation
-
# +DEBUG+:: low-level information for developers
-
#
-
# For instance, in a production system, you may have your Logger set to
-
# +INFO+ or even +WARN+
-
# When you are developing the system, however, you probably
-
# want to know about the program's internal state, and would set the Logger to
-
# +DEBUG+.
-
#
-
# *Note*: Logger does not escape or sanitize any messages passed to it.
-
# Developers should be aware of when potentially malicious data (user-input)
-
# is passed to Logger, and manually escape the untrusted data:
-
#
-
# logger.info("User-input: #{input.dump}")
-
# logger.info("User-input: %p" % input)
-
#
-
# You can use #formatter= for escaping all data.
-
#
-
# original_formatter = Logger::Formatter.new
-
# logger.formatter = proc { |severity, datetime, progname, msg|
-
# original_formatter.call(severity, datetime, progname, msg.dump)
-
# }
-
# logger.info(input)
-
#
-
# === Example
-
#
-
# This creates a logger to the standard output stream, with a level of +WARN+
-
#
-
# log = Logger.new(STDOUT)
-
# log.level = Logger::WARN
-
#
-
# log.debug("Created logger")
-
# log.info("Program started")
-
# log.warn("Nothing to do!")
-
#
-
# begin
-
# File.each_line(path) do |line|
-
# unless line =~ /^(\w+) = (.*)$/
-
# log.error("Line in wrong format: #{line}")
-
# end
-
# end
-
# rescue => err
-
# log.fatal("Caught exception; exiting")
-
# log.fatal(err)
-
# end
-
#
-
# Because the Logger's level is set to +WARN+, only the warning, error, and
-
# fatal messages are recorded. The debug and info messages are silently
-
# discarded.
-
#
-
# === Features
-
#
-
# There are several interesting features that Logger provides, like
-
# auto-rolling of log files, setting the format of log messages, and
-
# specifying a program name in conjunction with the message. The next section
-
# shows you how to achieve these things.
-
#
-
#
-
# == HOWTOs
-
#
-
# === How to create a logger
-
#
-
# The options below give you various choices, in more or less increasing
-
# complexity.
-
#
-
# 1. Create a logger which logs messages to STDERR/STDOUT.
-
#
-
# logger = Logger.new(STDERR)
-
# logger = Logger.new(STDOUT)
-
#
-
# 2. Create a logger for the file which has the specified name.
-
#
-
# logger = Logger.new('logfile.log')
-
#
-
# 3. Create a logger for the specified file.
-
#
-
# file = File.open('foo.log', File::WRONLY | File::APPEND)
-
# # To create new (and to remove old) logfile, add File::CREAT like;
-
# # file = open('foo.log', File::WRONLY | File::APPEND | File::CREAT)
-
# logger = Logger.new(file)
-
#
-
# 4. Create a logger which ages logfile once it reaches a certain size. Leave
-
# 10 "old log files" and each file is about 1,024,000 bytes.
-
#
-
# logger = Logger.new('foo.log', 10, 1024000)
-
#
-
# 5. Create a logger which ages logfile daily/weekly/monthly.
-
#
-
# logger = Logger.new('foo.log', 'daily')
-
# logger = Logger.new('foo.log', 'weekly')
-
# logger = Logger.new('foo.log', 'monthly')
-
#
-
# === How to log a message
-
#
-
# Notice the different methods (+fatal+, +error+, +info+) being used to log
-
# messages of various levels? Other methods in this family are +warn+ and
-
# +debug+. +add+ is used below to log a message of an arbitrary (perhaps
-
# dynamic) level.
-
#
-
# 1. Message in block.
-
#
-
# logger.fatal { "Argument 'foo' not given." }
-
#
-
# 2. Message as a string.
-
#
-
# logger.error "Argument #{ @foo } mismatch."
-
#
-
# 3. With progname.
-
#
-
# logger.info('initialize') { "Initializing..." }
-
#
-
# 4. With severity.
-
#
-
# logger.add(Logger::FATAL) { 'Fatal error!' }
-
#
-
# The block form allows you to create potentially complex log messages,
-
# but to delay their evaluation until and unless the message is
-
# logged. For example, if we have the following:
-
#
-
# logger.debug { "This is a " + potentially + " expensive operation" }
-
#
-
# If the logger's level is +INFO+ or higher, no debug messages will be logged,
-
# and the entire block will not even be evaluated. Compare to this:
-
#
-
# logger.debug("This is a " + potentially + " expensive operation")
-
#
-
# Here, the string concatenation is done every time, even if the log
-
# level is not set to show the debug message.
-
#
-
# === How to close a logger
-
#
-
# logger.close
-
#
-
# === Setting severity threshold
-
#
-
# 1. Original interface.
-
#
-
# logger.sev_threshold = Logger::WARN
-
#
-
# 2. Log4r (somewhat) compatible interface.
-
#
-
# logger.level = Logger::INFO
-
#
-
# DEBUG < INFO < WARN < ERROR < FATAL < UNKNOWN
-
#
-
#
-
# == Format
-
#
-
# Log messages are rendered in the output stream in a certain format by
-
# default. The default format and a sample are shown below:
-
#
-
# Log format:
-
# SeverityID, [Date Time mSec #pid] SeverityLabel -- ProgName: message
-
#
-
# Log sample:
-
# I, [Wed Mar 03 02:34:24 JST 1999 895701 #19074] INFO -- Main: info.
-
#
-
# You may change the date and time format via #datetime_format=
-
#
-
# logger.datetime_format = "%Y-%m-%d %H:%M:%S"
-
# # e.g. "2004-01-03 00:54:26"
-
#
-
# Or, you may change the overall format with #formatter= method.
-
#
-
# logger.formatter = proc do |severity, datetime, progname, msg|
-
# "#{datetime}: #{msg}\n"
-
# end
-
# # e.g. "Thu Sep 22 08:51:08 GMT+9:00 2005: hello world"
-
#
-
1
class Logger
-
1
VERSION = "1.2.7"
-
1
_, name, rev = %w$Id: logger.rb 31641 2011-05-19 00:07:25Z nobu $
-
1
if name
-
1
name = name.chomp(",v")
-
else
-
name = File.basename(__FILE__)
-
end
-
1
rev ||= "v#{VERSION}"
-
1
ProgName = "#{name}/#{rev}"
-
-
1
class Error < RuntimeError # :nodoc:
-
end
-
# not used after 1.2.7. just for compat.
-
1
class ShiftingError < Error # :nodoc:
-
end
-
-
# Logging severity.
-
1
module Severity
-
# Low-level information, mostly for developers
-
1
DEBUG = 0
-
# generic, useful information about system operation
-
1
INFO = 1
-
# a warning
-
1
WARN = 2
-
# a handleable error condition
-
1
ERROR = 3
-
# an unhandleable error that results in a program crash
-
1
FATAL = 4
-
# an unknown message that should always be logged
-
1
UNKNOWN = 5
-
end
-
1
include Severity
-
-
# Logging severity threshold (e.g. <tt>Logger::INFO</tt>).
-
1
attr_accessor :level
-
-
# program name to include in log messages.
-
1
attr_accessor :progname
-
-
# Set date-time format.
-
#
-
# +datetime_format+:: A string suitable for passing to +strftime+.
-
1
def datetime_format=(datetime_format)
-
@default_formatter.datetime_format = datetime_format
-
end
-
-
# Returns the date format being used. See #datetime_format=
-
1
def datetime_format
-
@default_formatter.datetime_format
-
end
-
-
# Logging formatter, as a +Proc+ that will take four arguments and
-
# return the formatted message. The arguments are:
-
#
-
# +severity+:: The Severity of the log message
-
# +time+:: A Time instance representing when the message was logged
-
# +progname+:: The #progname configured, or passed to the logger method
-
# +msg+:: The _Object_ the user passed to the log message; not necessarily a
-
# String.
-
#
-
# The block should return an Object that can be written to the logging
-
# device via +write+. The default formatter is used when no formatter is
-
# set.
-
1
attr_accessor :formatter
-
-
1
alias sev_threshold level
-
1
alias sev_threshold= level=
-
-
# Returns +true+ iff the current severity level allows for the printing of
-
# +DEBUG+ messages.
-
1399
def debug?; @level <= DEBUG; end
-
-
# Returns +true+ iff the current severity level allows for the printing of
-
# +INFO+ messages.
-
2
def info?; @level <= INFO; end
-
-
# Returns +true+ iff the current severity level allows for the printing of
-
# +WARN+ messages.
-
2
def warn?; @level <= WARN; end
-
-
# Returns +true+ iff the current severity level allows for the printing of
-
# +ERROR+ messages.
-
2
def error?; @level <= ERROR; end
-
-
# Returns +true+ iff the current severity level allows for the printing of
-
# +FATAL+ messages.
-
2
def fatal?; @level <= FATAL; end
-
-
#
-
# === Synopsis
-
#
-
# Logger.new(name, shift_age = 7, shift_size = 1048576)
-
# Logger.new(name, shift_age = 'weekly')
-
#
-
# === Args
-
#
-
# +logdev+::
-
# The log device. This is a filename (String) or IO object (typically
-
# +STDOUT+, +STDERR+, or an open file).
-
# +shift_age+::
-
# Number of old log files to keep, *or* frequency of rotation (+daily+,
-
# +weekly+ or +monthly+).
-
# +shift_size+::
-
# Maximum logfile size (only applies when +shift_age+ is a number).
-
#
-
# === Description
-
#
-
# Create an instance.
-
#
-
1
def initialize(logdev, shift_age = 0, shift_size = 1048576)
-
250
@progname = nil
-
250
@level = DEBUG
-
250
@default_formatter = Formatter.new
-
250
@formatter = nil
-
250
@logdev = nil
-
250
if logdev
-
250
@logdev = LogDevice.new(logdev, :shift_age => shift_age,
-
:shift_size => shift_size)
-
end
-
end
-
-
#
-
# === Synopsis
-
#
-
# Logger#add(severity, message = nil, progname = nil) { ... }
-
#
-
# === Args
-
#
-
# +severity+::
-
# Severity. Constants are defined in Logger namespace: +DEBUG+, +INFO+,
-
# +WARN+, +ERROR+, +FATAL+, or +UNKNOWN+.
-
# +message+::
-
# The log message. A String or Exception.
-
# +progname+::
-
# Program name string. Can be omitted. Treated as a message if no
-
# +message+ and +block+ are given.
-
# +block+::
-
# Can be omitted. Called to get a message string if +message+ is nil.
-
#
-
# === Return
-
#
-
# +true+ if successful, +false+ otherwise.
-
#
-
# When the given severity is not high enough (for this particular logger), log
-
# no message, and return +true+.
-
#
-
# === Description
-
#
-
# Log a message if the given severity is high enough. This is the generic
-
# logging method. Users will be more inclined to use #debug, #info, #warn,
-
# #error, and #fatal.
-
#
-
# <b>Message format</b>: +message+ can be any object, but it has to be
-
# converted to a String in order to log it. Generally, +inspect+ is used
-
# if the given object is not a String.
-
# A special case is an +Exception+ object, which will be printed in detail,
-
# including message, class, and backtrace. See #msg2str for the
-
# implementation if required.
-
#
-
# === Bugs
-
#
-
# * Logfile is not locked.
-
# * Append open does not need to lock file.
-
# * If the OS which supports multi I/O, records possibly be mixed.
-
#
-
1
def add(severity, message = nil, progname = nil, &block)
-
551
severity ||= UNKNOWN
-
551
if @logdev.nil? or severity < @level
-
162
return true
-
end
-
389
progname ||= @progname
-
389
if message.nil?
-
386
if block_given?
-
3
message = yield
-
else
-
383
message = progname
-
383
progname = @progname
-
end
-
end
-
389
@logdev.write(
-
format_message(format_severity(severity), Time.now, progname, message))
-
389
true
-
end
-
1
alias log add
-
-
#
-
# Dump given message to the log device without any formatting. If no log
-
# device exists, return +nil+.
-
#
-
1
def <<(msg)
-
unless @logdev.nil?
-
@logdev.write(msg)
-
end
-
end
-
-
#
-
# Log a +DEBUG+ message.
-
#
-
# See #info for more information.
-
#
-
1
def debug(progname = nil, &block)
-
516
add(DEBUG, nil, progname, &block)
-
end
-
-
#
-
# :call-seq:
-
# info(message)
-
# info(progname,&block)
-
#
-
# Log an +INFO+ message.
-
#
-
# +message+:: the message to log; does not need to be a String
-
# +progname+:: in the block form, this is the #progname to use in the
-
# the log message. The default can be set with #progname=
-
# <tt>&block</tt>:: evaluates to the message to log. This is not evaluated
-
# unless the logger's level is sufficient
-
# to log the message. This allows you to create
-
# potentially expensive logging messages that are
-
# only called when the logger is configured to show them.
-
#
-
# === Examples
-
#
-
# logger.info("MainApp") { "Received connection from #{ip}" }
-
# # ...
-
# logger.info "Waiting for input from user"
-
# # ...
-
# logger.info { "User typed #{input}" }
-
#
-
# You'll probably stick to the second form above, unless you want to provide a
-
# program name (which you can do with #progname= as well).
-
#
-
# === Return
-
#
-
# See #add.
-
#
-
1
def info(progname = nil, &block)
-
26
add(INFO, nil, progname, &block)
-
end
-
-
#
-
# Log a +WARN+ message.
-
#
-
# See #info for more information.
-
#
-
1
def warn(progname = nil, &block)
-
add(WARN, nil, progname, &block)
-
end
-
-
#
-
# Log an +ERROR+ message.
-
#
-
# See #info for more information.
-
#
-
1
def error(progname = nil, &block)
-
3
add(ERROR, nil, progname, &block)
-
end
-
-
#
-
# Log a +FATAL+ message.
-
#
-
# See #info for more information.
-
#
-
1
def fatal(progname = nil, &block)
-
add(FATAL, nil, progname, &block)
-
end
-
-
#
-
# Log an +UNKNOWN+ message. This will be printed no matter what the logger's
-
# level.
-
#
-
# See #info for more information.
-
#
-
1
def unknown(progname = nil, &block)
-
add(UNKNOWN, nil, progname, &block)
-
end
-
-
#
-
# Close the logging device.
-
#
-
1
def close
-
2
@logdev.close if @logdev
-
end
-
-
1
private
-
-
# Severity label for logging. (max 5 char)
-
1
SEV_LABEL = %w(DEBUG INFO WARN ERROR FATAL ANY)
-
-
1
def format_severity(severity)
-
389
SEV_LABEL[severity] || 'ANY'
-
end
-
-
1
def format_message(severity, datetime, progname, msg)
-
389
(@formatter || @default_formatter).call(severity, datetime, progname, msg)
-
end
-
-
-
# Default formatter for log messages
-
1
class Formatter
-
1
Format = "%s, [%s#%d] %5s -- %s: %s\n"
-
-
1
attr_accessor :datetime_format
-
-
1
def initialize
-
500
@datetime_format = nil
-
end
-
-
1
def call(severity, time, progname, msg)
-
Format % [severity[0..0], format_datetime(time), $$, severity, progname,
-
1
msg2str(msg)]
-
end
-
-
1
private
-
-
1
def format_datetime(time)
-
1
if @datetime_format.nil?
-
time.strftime("%Y-%m-%dT%H:%M:%S.") << "%06d " % time.usec
-
else
-
1
time.strftime(@datetime_format)
-
end
-
end
-
-
1
def msg2str(msg)
-
1
case msg
-
when ::String
-
1
msg
-
when ::Exception
-
"#{ msg.message } (#{ msg.class })\n" <<
-
(msg.backtrace || []).join("\n")
-
else
-
msg.inspect
-
end
-
end
-
end
-
-
-
# Device used for logging messages.
-
1
class LogDevice
-
1
attr_reader :dev
-
1
attr_reader :filename
-
-
1
class LogDeviceMutex
-
1
include MonitorMixin
-
end
-
-
1
def initialize(log = nil, opt = {})
-
250
@dev = @filename = @shift_age = @shift_size = nil
-
250
@mutex = LogDeviceMutex.new
-
250
if log.respond_to?(:write) and log.respond_to?(:close)
-
101
@dev = log
-
else
-
149
@dev = open_logfile(log)
-
149
@dev.sync = true
-
149
@filename = log
-
149
@shift_age = opt[:shift_age] || 7
-
149
@shift_size = opt[:shift_size] || 1048576
-
end
-
end
-
-
1
def write(message)
-
389
begin
-
389
@mutex.synchronize do
-
389
if @shift_age and @dev.respond_to?(:stat)
-
206
begin
-
206
check_shift_log
-
rescue
-
warn("log shifting failed. #{$!}")
-
end
-
end
-
389
begin
-
389
@dev.write(message)
-
rescue
-
warn("log writing failed. #{$!}")
-
end
-
end
-
rescue Exception => ignored
-
warn("log writing failed. #{ignored}")
-
end
-
end
-
-
1
def close
-
2
begin
-
2
@mutex.synchronize do
-
2
@dev.close rescue nil
-
end
-
rescue Exception
-
@dev.close rescue nil
-
end
-
end
-
-
1
private
-
-
1
def open_logfile(filename)
-
149
if (FileTest.exist?(filename))
-
149
open(filename, (File::WRONLY | File::APPEND))
-
else
-
create_logfile(filename)
-
end
-
end
-
-
1
def create_logfile(filename)
-
logdev = open(filename, (File::WRONLY | File::APPEND | File::CREAT))
-
logdev.sync = true
-
add_log_header(logdev)
-
logdev
-
end
-
-
1
def add_log_header(file)
-
file.write(
-
"# Logfile created on %s by %s\n" % [Time.now.to_s, Logger::ProgName]
-
)
-
end
-
-
1
SiD = 24 * 60 * 60
-
-
1
def check_shift_log
-
206
if @shift_age.is_a?(Integer)
-
# Note: always returns false if '0'.
-
206
if @filename && (@shift_age > 0) && (@dev.stat.size > @shift_size)
-
shift_log_age
-
end
-
else
-
now = Time.now
-
period_end = previous_period_end(now)
-
if @dev.stat.mtime <= period_end
-
shift_log_period(period_end)
-
end
-
end
-
end
-
-
1
def shift_log_age
-
(@shift_age-3).downto(0) do |i|
-
if FileTest.exist?("#{@filename}.#{i}")
-
File.rename("#{@filename}.#{i}", "#{@filename}.#{i+1}")
-
end
-
end
-
@dev.close rescue nil
-
File.rename("#{@filename}", "#{@filename}.0")
-
@dev = create_logfile(@filename)
-
return true
-
end
-
-
1
def shift_log_period(period_end)
-
postfix = period_end.strftime("%Y%m%d") # YYYYMMDD
-
age_file = "#{@filename}.#{postfix}"
-
if FileTest.exist?(age_file)
-
# try to avoid filename crash caused by Timestamp change.
-
idx = 0
-
# .99 can be overridden; avoid too much file search with 'loop do'
-
while idx < 100
-
idx += 1
-
age_file = "#{@filename}.#{postfix}.#{idx}"
-
break unless FileTest.exist?(age_file)
-
end
-
end
-
@dev.close rescue nil
-
File.rename("#{@filename}", age_file)
-
@dev = create_logfile(@filename)
-
return true
-
end
-
-
1
def previous_period_end(now)
-
case @shift_age
-
when /^daily$/
-
eod(now - 1 * SiD)
-
when /^weekly$/
-
eod(now - ((now.wday + 1) * SiD))
-
when /^monthly$/
-
eod(now - now.mday * SiD)
-
else
-
now
-
end
-
end
-
-
1
def eod(t)
-
Time.mktime(t.year, t.month, t.mday, 23, 59, 59)
-
end
-
end
-
-
-
#
-
# == Description
-
#
-
# Application -- Add logging support to your application.
-
#
-
# == Usage
-
#
-
# 1. Define your application class as a sub-class of this class.
-
# 2. Override 'run' method in your class to do many things.
-
# 3. Instantiate it and invoke 'start'.
-
#
-
# == Example
-
#
-
# class FooApp < Application
-
# def initialize(foo_app, application_specific, arguments)
-
# super('FooApp') # Name of the application.
-
# end
-
#
-
# def run
-
# ...
-
# log(WARN, 'warning', 'my_method1')
-
# ...
-
# @log.error('my_method2') { 'Error!' }
-
# ...
-
# end
-
# end
-
#
-
# status = FooApp.new(....).start
-
#
-
1
class Application
-
1
include Logger::Severity
-
-
# Name of the application given at initialize.
-
1
attr_reader :appname
-
-
#
-
# == Synopsis
-
#
-
# Application.new(appname = '')
-
#
-
# == Args
-
#
-
# +appname+:: Name of the application.
-
#
-
# == Description
-
#
-
# Create an instance. Log device is +STDERR+ by default. This can be
-
# changed with #set_log.
-
#
-
1
def initialize(appname = nil)
-
@appname = appname
-
@log = Logger.new(STDERR)
-
@log.progname = @appname
-
@level = @log.level
-
end
-
-
#
-
# Start the application. Return the status code.
-
#
-
1
def start
-
status = -1
-
begin
-
log(INFO, "Start of #{ @appname }.")
-
status = run
-
rescue
-
log(FATAL, "Detected an exception. Stopping ... #{$!} (#{$!.class})\n" << $@.join("\n"))
-
ensure
-
log(INFO, "End of #{ @appname }. (status: #{ status.to_s })")
-
end
-
status
-
end
-
-
# Logger for this application. See the class Logger for an explanation.
-
1
def logger
-
@log
-
end
-
-
#
-
# Sets the logger for this application. See the class Logger for an
-
# explanation.
-
#
-
1
def logger=(logger)
-
@log = logger
-
@log.progname = @appname
-
@log.level = @level
-
end
-
-
#
-
# Sets the log device for this application. See <tt>Logger.new</tt> for
-
# an explanation of the arguments.
-
#
-
1
def set_log(logdev, shift_age = 0, shift_size = 1024000)
-
@log = Logger.new(logdev, shift_age, shift_size)
-
@log.progname = @appname
-
@log.level = @level
-
end
-
-
1
def log=(logdev)
-
set_log(logdev)
-
end
-
-
#
-
# Set the logging threshold, just like <tt>Logger#level=</tt>.
-
#
-
1
def level=(level)
-
@level = level
-
@log.level = @level
-
end
-
-
#
-
# See Logger#add. This application's +appname+ is used.
-
#
-
1
def log(severity, message = nil, &block)
-
@log.add(severity, message, @appname, &block) if @log
-
end
-
-
1
private
-
-
1
def run
-
# TODO: should be an NotImplementedError
-
raise RuntimeError.new('Method run must be defined in the derived class.')
-
end
-
end
-
end
-
#
-
# mutex_m.rb -
-
# $Release Version: 3.0$
-
# $Revision: 1.7 $
-
# Original from mutex.rb
-
# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-
# modified by matz
-
# patched by akira yamada
-
#
-
# --
-
# Usage:
-
# require "mutex_m.rb"
-
# obj = Object.new
-
# obj.extend Mutex_m
-
# ...
-
# extended object can be handled like Mutex
-
# or
-
# class Foo
-
# include Mutex_m
-
# ...
-
# end
-
# obj = Foo.new
-
# this obj can be handled like Mutex
-
#
-
-
1
require 'thread'
-
-
1
module Mutex_m
-
1
def Mutex_m.define_aliases(cl)
-
1
cl.module_eval %q{
-
alias locked? mu_locked?
-
alias lock mu_lock
-
alias unlock mu_unlock
-
alias try_lock mu_try_lock
-
alias synchronize mu_synchronize
-
}
-
end
-
-
1
def Mutex_m.append_features(cl)
-
1
super
-
1
define_aliases(cl) unless cl.instance_of?(Module)
-
end
-
-
1
def Mutex_m.extend_object(obj)
-
super
-
obj.mu_extended
-
end
-
-
1
def mu_extended
-
unless (defined? locked? and
-
defined? lock and
-
defined? unlock and
-
defined? try_lock and
-
defined? synchronize)
-
Mutex_m.define_aliases(singleton_class)
-
end
-
mu_initialize
-
end
-
-
# locking
-
1
def mu_synchronize(&block)
-
179
@_mutex.synchronize(&block)
-
end
-
-
1
def mu_locked?
-
@_mutex.locked?
-
end
-
-
1
def mu_try_lock
-
@_mutex.try_lock
-
end
-
-
1
def mu_lock
-
@_mutex.lock
-
end
-
-
1
def mu_unlock
-
@_mutex.unlock
-
end
-
-
1
def sleep(timeout = nil)
-
@_mutex.sleep(timeout)
-
end
-
-
1
private
-
-
1
def mu_initialize
-
35
@_mutex = Mutex.new
-
end
-
-
1
def initialize(*args)
-
35
mu_initialize
-
35
super
-
end
-
end
-
=begin
-
= $RCSfile$ -- Loader for all OpenSSL C-space and Ruby-space definitions
-
-
= Info
-
'OpenSSL for Ruby 2' project
-
Copyright (C) 2002 Michal Rokos <m.rokos@sh.cvut.cz>
-
All rights reserved.
-
-
= Licence
-
This program is licenced under the same licence as Ruby.
-
(See the file 'LICENCE'.)
-
-
= Version
-
$Id: openssl.rb 32665 2011-07-25 06:38:44Z nahi $
-
=end
-
-
1
require 'openssl.so'
-
-
1
require 'openssl/bn'
-
1
require 'openssl/cipher'
-
1
require 'openssl/config'
-
1
require 'openssl/digest'
-
1
require 'openssl/ssl-internal'
-
1
require 'openssl/x509-internal'
-
-
#--
-
#
-
# $RCSfile$
-
#
-
# = Ruby-space definitions that completes C-space funcs for BN
-
#
-
# = Info
-
# 'OpenSSL for Ruby 2' project
-
# Copyright (C) 2002 Michal Rokos <m.rokos@sh.cvut.cz>
-
# All rights reserved.
-
#
-
# = Licence
-
# This program is licenced under the same licence as Ruby.
-
# (See the file 'LICENCE'.)
-
#
-
# = Version
-
# $Id: bn.rb 33067 2011-08-25 00:52:10Z drbrain $
-
#
-
#++
-
-
1
module OpenSSL
-
1
class BN
-
1
include Comparable
-
end # BN
-
end # OpenSSL
-
-
##
-
# Add double dispatch to Integer
-
#
-
1
class Integer
-
1
def to_bn
-
OpenSSL::BN::new(self.to_s(16), 16)
-
end
-
end # Integer
-
-
=begin
-
= $RCSfile$ -- Buffering mix-in module.
-
-
= Info
-
'OpenSSL for Ruby 2' project
-
Copyright (C) 2001 GOTOU YUUZOU <gotoyuzo@notwork.org>
-
All rights reserved.
-
-
= Licence
-
This program is licenced under the same licence as Ruby.
-
(See the file 'LICENCE'.)
-
-
= Version
-
$Id: buffering.rb 32012 2011-06-11 14:07:42Z nahi $
-
=end
-
-
##
-
# OpenSSL IO buffering mix-in module.
-
#
-
# This module allows an OpenSSL::SSL::SSLSocket to behave like an IO.
-
-
1
module OpenSSL::Buffering
-
1
include Enumerable
-
-
##
-
# The "sync mode" of the SSLSocket.
-
#
-
# See IO#sync for full details.
-
-
1
attr_accessor :sync
-
-
##
-
# Default size to read from or write to the SSLSocket for buffer operations.
-
-
1
BLOCK_SIZE = 1024*16
-
-
1
def initialize(*args)
-
@eof = false
-
@rbuffer = ""
-
@sync = @io.sync
-
end
-
-
#
-
# for reading.
-
#
-
1
private
-
-
##
-
# Fills the buffer from the underlying SSLSocket
-
-
1
def fill_rbuff
-
begin
-
@rbuffer << self.sysread(BLOCK_SIZE)
-
rescue Errno::EAGAIN
-
retry
-
rescue EOFError
-
@eof = true
-
end
-
end
-
-
##
-
# Consumes +size+ bytes from the buffer
-
-
1
def consume_rbuff(size=nil)
-
if @rbuffer.empty?
-
nil
-
else
-
size = @rbuffer.size unless size
-
ret = @rbuffer[0, size]
-
@rbuffer[0, size] = ""
-
ret
-
end
-
end
-
-
1
public
-
-
##
-
# Reads +size+ bytes from the stream. If +buf+ is provided it must
-
# reference a string which will receive the data.
-
#
-
# See IO#read for full details.
-
-
1
def read(size=nil, buf=nil)
-
if size == 0
-
if buf
-
buf.clear
-
return buf
-
else
-
return ""
-
end
-
end
-
until @eof
-
break if size && size <= @rbuffer.size
-
fill_rbuff
-
end
-
ret = consume_rbuff(size) || ""
-
if buf
-
buf.replace(ret)
-
ret = buf
-
end
-
(size && ret.empty?) ? nil : ret
-
end
-
-
##
-
# Reads at most +maxlen+ bytes from the stream. If +buf+ is provided it
-
# must reference a string which will receive the data.
-
#
-
# See IO#readpartial for full details.
-
-
1
def readpartial(maxlen, buf=nil)
-
if maxlen == 0
-
if buf
-
buf.clear
-
return buf
-
else
-
return ""
-
end
-
end
-
if @rbuffer.empty?
-
begin
-
return sysread(maxlen, buf)
-
rescue Errno::EAGAIN
-
retry
-
end
-
end
-
ret = consume_rbuff(maxlen)
-
if buf
-
buf.replace(ret)
-
ret = buf
-
end
-
raise EOFError if ret.empty?
-
ret
-
end
-
-
##
-
# Reads at most +maxlen+ bytes in the non-blocking manner.
-
#
-
# When no data can be read without blocking it raises
-
# OpenSSL::SSL::SSLError extended by IO::WaitReadable or IO::WaitWritable.
-
#
-
# IO::WaitReadable means SSL needs to read internally so read_nonblock
-
# should be called again when the underlying IO is readable.
-
#
-
# IO::WaitWritable means SSL needs to write internally so read_nonblock
-
# should be called again after the underlying IO is writable.
-
#
-
# OpenSSL::Buffering#read_nonblock needs two rescue clause as follows:
-
#
-
# # emulates blocking read (readpartial).
-
# begin
-
# result = ssl.read_nonblock(maxlen)
-
# rescue IO::WaitReadable
-
# IO.select([io])
-
# retry
-
# rescue IO::WaitWritable
-
# IO.select(nil, [io])
-
# retry
-
# end
-
#
-
# Note that one reason that read_nonblock writes to the underlying IO is
-
# when the peer requests a new TLS/SSL handshake. See openssl the FAQ for
-
# more details. http://www.openssl.org/support/faq.html
-
-
1
def read_nonblock(maxlen, buf=nil)
-
if maxlen == 0
-
if buf
-
buf.clear
-
return buf
-
else
-
return ""
-
end
-
end
-
if @rbuffer.empty?
-
return sysread_nonblock(maxlen, buf)
-
end
-
ret = consume_rbuff(maxlen)
-
if buf
-
buf.replace(ret)
-
ret = buf
-
end
-
raise EOFError if ret.empty?
-
ret
-
end
-
-
##
-
# Reads the next "line+ from the stream. Lines are separated by +eol+. If
-
# +limit+ is provided the result will not be longer than the given number of
-
# bytes.
-
#
-
# +eol+ may be a String or Regexp.
-
#
-
# Unlike IO#gets the line read will not be assigned to +$_+.
-
#
-
# Unlike IO#gets the separator must be provided if a limit is provided.
-
-
1
def gets(eol=$/, limit=nil)
-
idx = @rbuffer.index(eol)
-
until @eof
-
break if idx
-
fill_rbuff
-
idx = @rbuffer.index(eol)
-
end
-
if eol.is_a?(Regexp)
-
size = idx ? idx+$&.size : nil
-
else
-
size = idx ? idx+eol.size : nil
-
end
-
if limit and limit >= 0
-
size = [size, limit].min
-
end
-
consume_rbuff(size)
-
end
-
-
##
-
# Executes the block for every line in the stream where lines are separated
-
# by +eol+.
-
#
-
# See also #gets
-
-
1
def each(eol=$/)
-
while line = self.gets(eol)
-
yield line
-
end
-
end
-
1
alias each_line each
-
-
##
-
# Reads lines from the stream which are separated by +eol+.
-
#
-
# See also #gets
-
-
1
def readlines(eol=$/)
-
ary = []
-
while line = self.gets(eol)
-
ary << line
-
end
-
ary
-
end
-
-
##
-
# Reads a line from the stream which is separated by +eol+.
-
#
-
# Raises EOFError if at end of file.
-
-
1
def readline(eol=$/)
-
raise EOFError if eof?
-
gets(eol)
-
end
-
-
##
-
# Reads one character from the stream. Returns nil if called at end of
-
# file.
-
-
1
def getc
-
read(1)
-
end
-
-
##
-
# Calls the given block once for each byte in the stream.
-
-
1
def each_byte # :yields: byte
-
while c = getc
-
yield(c.ord)
-
end
-
end
-
-
##
-
# Reads a one-character string from the stream. Raises an EOFError at end
-
# of file.
-
-
1
def readchar
-
raise EOFError if eof?
-
getc
-
end
-
-
##
-
# Pushes character +c+ back onto the stream such that a subsequent buffered
-
# character read will return it.
-
#
-
# Unlike IO#getc multiple bytes may be pushed back onto the stream.
-
#
-
# Has no effect on unbuffered reads (such as #sysread).
-
-
1
def ungetc(c)
-
@rbuffer[0,0] = c.chr
-
end
-
-
##
-
# Returns true if the stream is at file which means there is no more data to
-
# be read.
-
-
1
def eof?
-
fill_rbuff if !@eof && @rbuffer.empty?
-
@eof && @rbuffer.empty?
-
end
-
1
alias eof eof?
-
-
#
-
# for writing.
-
#
-
1
private
-
-
##
-
# Writes +s+ to the buffer. When the buffer is full or #sync is true the
-
# buffer is flushed to the underlying socket.
-
-
1
def do_write(s)
-
@wbuffer = "" unless defined? @wbuffer
-
@wbuffer << s
-
@sync ||= false
-
if @sync or @wbuffer.size > BLOCK_SIZE or idx = @wbuffer.rindex($/)
-
remain = idx ? idx + $/.size : @wbuffer.length
-
nwritten = 0
-
while remain > 0
-
str = @wbuffer[nwritten,remain]
-
begin
-
nwrote = syswrite(str)
-
rescue Errno::EAGAIN
-
retry
-
end
-
remain -= nwrote
-
nwritten += nwrote
-
end
-
@wbuffer[0,nwritten] = ""
-
end
-
end
-
-
1
public
-
-
##
-
# Writes +s+ to the stream. If the argument is not a string it will be
-
# converted using String#to_s. Returns the number of bytes written.
-
-
1
def write(s)
-
do_write(s)
-
s.length
-
end
-
-
##
-
# Writes +str+ in the non-blocking manner.
-
#
-
# If there is buffered data, it is flushed first. This may block.
-
#
-
# write_nonblock returns number of bytes written to the SSL connection.
-
#
-
# When no data can be written without blocking it raises
-
# OpenSSL::SSL::SSLError extended by IO::WaitReadable or IO::WaitWritable.
-
#
-
# IO::WaitReadable means SSL needs to read internally so write_nonblock
-
# should be called again after the underlying IO is readable.
-
#
-
# IO::WaitWritable means SSL needs to write internally so write_nonblock
-
# should be called again after underlying IO is writable.
-
#
-
# So OpenSSL::Buffering#write_nonblock needs two rescue clause as follows.
-
#
-
# # emulates blocking write.
-
# begin
-
# result = ssl.write_nonblock(str)
-
# rescue IO::WaitReadable
-
# IO.select([io])
-
# retry
-
# rescue IO::WaitWritable
-
# IO.select(nil, [io])
-
# retry
-
# end
-
#
-
# Note that one reason that write_nonblock reads from the underlying IO
-
# is when the peer requests a new TLS/SSL handshake. See the openssl FAQ
-
# for more details. http://www.openssl.org/support/faq.html
-
-
1
def write_nonblock(s)
-
flush
-
syswrite_nonblock(s)
-
end
-
-
##
-
# Writes +s+ to the stream. +s+ will be converted to a String using
-
# String#to_s.
-
-
1
def << (s)
-
do_write(s)
-
self
-
end
-
-
##
-
# Writes +args+ to the stream along with a record separator.
-
#
-
# See IO#puts for full details.
-
-
1
def puts(*args)
-
s = ""
-
if args.empty?
-
s << "\n"
-
end
-
args.each{|arg|
-
s << arg.to_s
-
if $/ && /\n\z/ !~ s
-
s << "\n"
-
end
-
}
-
do_write(s)
-
nil
-
end
-
-
##
-
# Writes +args+ to the stream.
-
#
-
# See IO#print for full details.
-
-
1
def print(*args)
-
s = ""
-
args.each{ |arg| s << arg.to_s }
-
do_write(s)
-
nil
-
end
-
-
##
-
# Formats and writes to the stream converting parameters under control of
-
# the format string.
-
#
-
# See Kernel#sprintf for format string details.
-
-
1
def printf(s, *args)
-
do_write(s % args)
-
nil
-
end
-
-
##
-
# Flushes buffered data to the SSLSocket.
-
-
1
def flush
-
osync = @sync
-
@sync = true
-
do_write ""
-
return self
-
ensure
-
@sync = osync
-
end
-
-
##
-
# Closes the SSLSocket and flushes any unwritten data.
-
-
1
def close
-
flush rescue nil
-
sysclose
-
end
-
end
-
#--
-
#
-
# $RCSfile$
-
#
-
# = Ruby-space predefined Cipher subclasses
-
#
-
# = Info
-
# 'OpenSSL for Ruby 2' project
-
# Copyright (C) 2002 Michal Rokos <m.rokos@sh.cvut.cz>
-
# All rights reserved.
-
#
-
# = Licence
-
# This program is licenced under the same licence as Ruby.
-
# (See the file 'LICENCE'.)
-
#
-
# = Version
-
# $Id: cipher.rb 33067 2011-08-25 00:52:10Z drbrain $
-
#
-
#++
-
-
1
module OpenSSL
-
1
class Cipher
-
1
%w(AES CAST5 BF DES IDEA RC2 RC4 RC5).each{|name|
-
8
klass = Class.new(Cipher){
-
8
define_method(:initialize){|*args|
-
cipher_name = args.inject(name){|n, arg| "#{n}-#{arg}" }
-
super(cipher_name)
-
}
-
}
-
8
const_set(name, klass)
-
}
-
-
1
%w(128 192 256).each{|keylen|
-
3
klass = Class.new(Cipher){
-
3
define_method(:initialize){|mode|
-
mode ||= "CBC"
-
cipher_name = "AES-#{keylen}-#{mode}"
-
super(cipher_name)
-
}
-
}
-
3
const_set("AES#{keylen}", klass)
-
}
-
-
# Generate, set, and return a random key.
-
# You must call cipher.encrypt or cipher.decrypt before calling this method.
-
1
def random_key
-
str = OpenSSL::Random.random_bytes(self.key_len)
-
self.key = str
-
return str
-
end
-
-
# Generate, set, and return a random iv.
-
# You must call cipher.encrypt or cipher.decrypt before calling this method.
-
1
def random_iv
-
6
str = OpenSSL::Random.random_bytes(self.iv_len)
-
6
self.iv = str
-
6
return str
-
end
-
-
# This class is only provided for backwards compatibility. Use OpenSSL::Cipher in the future.
-
1
class Cipher < Cipher
-
# add warning
-
end
-
end # Cipher
-
end # OpenSSL
-
=begin
-
= Ruby-space definitions that completes C-space funcs for Config
-
-
= Info
-
Copyright (C) 2010 Hiroshi Nakamura <nahi@ruby-lang.org>
-
-
= Licence
-
This program is licenced under the same licence as Ruby.
-
(See the file 'LICENCE'.)
-
-
=end
-
-
1
require 'stringio'
-
-
1
module OpenSSL
-
1
class Config
-
1
include Enumerable
-
-
1
class << self
-
1
def parse(str)
-
c = new()
-
parse_config(StringIO.new(str)).each do |section, hash|
-
c[section] = hash
-
end
-
c
-
end
-
-
1
alias load new
-
-
1
def parse_config(io)
-
begin
-
parse_config_lines(io)
-
rescue ConfigError => e
-
e.message.replace("error in line #{io.lineno}: " + e.message)
-
raise
-
end
-
end
-
-
1
def get_key_string(data, section, key) # :nodoc:
-
if v = data[section] && data[section][key]
-
return v
-
elsif section == 'ENV'
-
if v = ENV[key]
-
return v
-
end
-
end
-
if v = data['default'] && data['default'][key]
-
return v
-
end
-
end
-
-
1
private
-
-
1
def parse_config_lines(io)
-
section = 'default'
-
data = {section => {}}
-
while definition = get_definition(io)
-
definition = clear_comments(definition)
-
next if definition.empty?
-
if definition[0] == ?[
-
if /\[([^\]]*)\]/ =~ definition
-
section = $1.strip
-
data[section] ||= {}
-
else
-
raise ConfigError, "missing close square bracket"
-
end
-
else
-
if /\A([^:\s]*)(?:::([^:\s]*))?\s*=(.*)\z/ =~ definition
-
if $2
-
section = $1
-
key = $2
-
else
-
key = $1
-
end
-
value = unescape_value(data, section, $3)
-
(data[section] ||= {})[key] = value.strip
-
else
-
raise ConfigError, "missing equal sign"
-
end
-
end
-
end
-
data
-
end
-
-
# escape with backslash
-
1
QUOTE_REGEXP_SQ = /\A([^'\\]*(?:\\.[^'\\]*)*)'/
-
# escape with backslash and doubled dq
-
1
QUOTE_REGEXP_DQ = /\A([^"\\]*(?:""[^"\\]*|\\.[^"\\]*)*)"/
-
# escaped char map
-
1
ESCAPE_MAP = {
-
"r" => "\r",
-
"n" => "\n",
-
"b" => "\b",
-
"t" => "\t",
-
}
-
-
1
def unescape_value(data, section, value)
-
scanned = []
-
while m = value.match(/['"\\$]/)
-
scanned << m.pre_match
-
c = m[0]
-
value = m.post_match
-
case c
-
when "'"
-
if m = value.match(QUOTE_REGEXP_SQ)
-
scanned << m[1].gsub(/\\(.)/, '\\1')
-
value = m.post_match
-
else
-
break
-
end
-
when '"'
-
if m = value.match(QUOTE_REGEXP_DQ)
-
scanned << m[1].gsub(/""/, '').gsub(/\\(.)/, '\\1')
-
value = m.post_match
-
else
-
break
-
end
-
when "\\"
-
c = value.slice!(0, 1)
-
scanned << (ESCAPE_MAP[c] || c)
-
when "$"
-
ref, value = extract_reference(value)
-
refsec = section
-
if ref.index('::')
-
refsec, ref = ref.split('::', 2)
-
end
-
if v = get_key_string(data, refsec, ref)
-
scanned << v
-
else
-
raise ConfigError, "variable has no value"
-
end
-
else
-
raise 'must not reaced'
-
end
-
end
-
scanned << value
-
scanned.join
-
end
-
-
1
def extract_reference(value)
-
rest = ''
-
if m = value.match(/\(([^)]*)\)|\{([^}]*)\}/)
-
value = m[1] || m[2]
-
rest = m.post_match
-
elsif [?(, ?{].include?(value[0])
-
raise ConfigError, "no close brace"
-
end
-
if m = value.match(/[a-zA-Z0-9_]*(?:::[a-zA-Z0-9_]*)?/)
-
return m[0], m.post_match + rest
-
else
-
raise
-
end
-
end
-
-
1
def clear_comments(line)
-
# FCOMMENT
-
if m = line.match(/\A([\t\n\f ]*);.*\z/)
-
return m[1]
-
end
-
# COMMENT
-
scanned = []
-
while m = line.match(/[#'"\\]/)
-
scanned << m.pre_match
-
c = m[0]
-
line = m.post_match
-
case c
-
when '#'
-
line = nil
-
break
-
when "'", '"'
-
regexp = (c == "'") ? QUOTE_REGEXP_SQ : QUOTE_REGEXP_DQ
-
scanned << c
-
if m = line.match(regexp)
-
scanned << m[0]
-
line = m.post_match
-
else
-
scanned << line
-
line = nil
-
break
-
end
-
when "\\"
-
scanned << c
-
scanned << line.slice!(0, 1)
-
else
-
raise 'must not reaced'
-
end
-
end
-
scanned << line
-
scanned.join
-
end
-
-
1
def get_definition(io)
-
if line = get_line(io)
-
while /[^\\]\\\z/ =~ line
-
if extra = get_line(io)
-
line += extra
-
else
-
break
-
end
-
end
-
return line.strip
-
end
-
end
-
-
1
def get_line(io)
-
if line = io.gets
-
line.gsub(/[\r\n]*/, '')
-
end
-
end
-
end
-
-
1
def initialize(filename = nil)
-
@data = {}
-
if filename
-
File.open(filename.to_s) do |file|
-
Config.parse_config(file).each do |section, hash|
-
self[section] = hash
-
end
-
end
-
end
-
end
-
-
1
def get_value(section, key)
-
if section.nil?
-
raise TypeError.new('nil not allowed')
-
end
-
section = 'default' if section.empty?
-
get_key_string(section, key)
-
end
-
-
1
def value(arg1, arg2 = nil)
-
warn('Config#value is deprecated; use Config#get_value')
-
if arg2.nil?
-
section, key = 'default', arg1
-
else
-
section, key = arg1, arg2
-
end
-
section ||= 'default'
-
section = 'default' if section.empty?
-
get_key_string(section, key)
-
end
-
-
1
def add_value(section, key, value)
-
check_modify
-
(@data[section] ||= {})[key] = value
-
end
-
-
1
def [](section)
-
@data[section] || {}
-
end
-
-
1
def section(name)
-
warn('Config#section is deprecated; use Config#[]')
-
@data[name] || {}
-
end
-
-
1
def []=(section, pairs)
-
check_modify
-
@data[section] ||= {}
-
pairs.each do |key, value|
-
self.add_value(section, key, value)
-
end
-
end
-
-
1
def sections
-
@data.keys
-
end
-
-
1
def to_s
-
ary = []
-
@data.keys.sort.each do |section|
-
ary << "[ #{section} ]\n"
-
@data[section].keys.each do |key|
-
ary << "#{key}=#{@data[section][key]}\n"
-
end
-
ary << "\n"
-
end
-
ary.join
-
end
-
-
1
def each
-
@data.each do |section, hash|
-
hash.each do |key, value|
-
yield [section, key, value]
-
end
-
end
-
end
-
-
1
def inspect
-
"#<#{self.class.name} sections=#{sections.inspect}>"
-
end
-
-
1
protected
-
-
1
def data
-
@data
-
end
-
-
1
private
-
-
1
def initialize_copy(other)
-
@data = other.data.dup
-
end
-
-
1
def check_modify
-
raise TypeError.new("Insecure: can't modify OpenSSL config") if frozen?
-
end
-
-
1
def get_key_string(section, key)
-
Config.get_key_string(@data, section, key)
-
end
-
end
-
end
-
#--
-
#
-
# $RCSfile$
-
#
-
# = Ruby-space predefined Digest subclasses
-
#
-
# = Info
-
# 'OpenSSL for Ruby 2' project
-
# Copyright (C) 2002 Michal Rokos <m.rokos@sh.cvut.cz>
-
# All rights reserved.
-
#
-
# = Licence
-
# This program is licenced under the same licence as Ruby.
-
# (See the file 'LICENCE'.)
-
#
-
# = Version
-
# $Id: digest.rb 33067 2011-08-25 00:52:10Z drbrain $
-
#
-
#++
-
-
1
module OpenSSL
-
1
class Digest
-
-
1
alg = %w(DSS DSS1 MD2 MD4 MD5 MDC2 RIPEMD160 SHA SHA1)
-
1
if OPENSSL_VERSION_NUMBER > 0x00908000
-
1
alg += %w(SHA224 SHA256 SHA384 SHA512)
-
end
-
-
# Return the +data+ hash computed with +name+ Digest. +name+ is either the
-
# long name or short name of a supported digest algorithm.
-
#
-
# === Examples
-
#
-
# OpenSSL::Digest.digest("SHA256, "abc")
-
#
-
# which is equivalent to:
-
#
-
# OpenSSL::Digest::SHA256.digest("abc")
-
-
1
def self.digest(name, data)
-
super(data, name)
-
end
-
-
1
alg.each{|name|
-
13
klass = Class.new(Digest){
-
13
define_method(:initialize){|*data|
-
29
if data.length > 1
-
raise ArgumentError,
-
"wrong number of arguments (#{data.length} for 1)"
-
end
-
29
super(name, data.first)
-
}
-
}
-
26
singleton = (class << klass; self; end)
-
13
singleton.class_eval{
-
13
define_method(:digest){|data| Digest.digest(name, data) }
-
13
define_method(:hexdigest){|data| Digest.hexdigest(name, data) }
-
}
-
13
const_set(name, klass)
-
}
-
-
# This class is only provided for backwards compatibility. Use OpenSSL::Digest in the future.
-
1
class Digest < Digest
-
1
def initialize(*args)
-
# add warning
-
super(*args)
-
end
-
end
-
-
end # Digest
-
end # OpenSSL
-
-
=begin
-
= $RCSfile$ -- Ruby-space definitions that completes C-space funcs for SSL
-
-
= Info
-
'OpenSSL for Ruby 2' project
-
Copyright (C) 2001 GOTOU YUUZOU <gotoyuzo@notwork.org>
-
All rights reserved.
-
-
= Licence
-
This program is licenced under the same licence as Ruby.
-
(See the file 'LICENCE'.)
-
-
= Version
-
$Id: ssl-internal.rb 29189 2010-09-06 01:53:00Z nahi $
-
=end
-
-
1
require "openssl/buffering"
-
1
require "fcntl"
-
-
1
module OpenSSL
-
1
module SSL
-
1
class SSLContext
-
1
DEFAULT_PARAMS = {
-
:ssl_version => "SSLv23",
-
:verify_mode => OpenSSL::SSL::VERIFY_PEER,
-
:ciphers => "ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW",
-
:options => OpenSSL::SSL::OP_ALL,
-
}
-
-
1
DEFAULT_CERT_STORE = OpenSSL::X509::Store.new
-
1
DEFAULT_CERT_STORE.set_default_paths
-
1
if defined?(OpenSSL::X509::V_FLAG_CRL_CHECK_ALL)
-
1
DEFAULT_CERT_STORE.flags = OpenSSL::X509::V_FLAG_CRL_CHECK_ALL
-
end
-
-
1
def set_params(params={})
-
params = DEFAULT_PARAMS.merge(params)
-
params.each{|name, value| self.__send__("#{name}=", value) }
-
if self.verify_mode != OpenSSL::SSL::VERIFY_NONE
-
unless self.ca_file or self.ca_path or self.cert_store
-
self.cert_store = DEFAULT_CERT_STORE
-
end
-
end
-
return params
-
end
-
end
-
-
1
module SocketForwarder
-
1
def addr
-
to_io.addr
-
end
-
-
1
def peeraddr
-
to_io.peeraddr
-
end
-
-
1
def setsockopt(level, optname, optval)
-
to_io.setsockopt(level, optname, optval)
-
end
-
-
1
def getsockopt(level, optname)
-
to_io.getsockopt(level, optname)
-
end
-
-
1
def fcntl(*args)
-
to_io.fcntl(*args)
-
end
-
-
1
def closed?
-
to_io.closed?
-
end
-
-
1
def do_not_reverse_lookup=(flag)
-
to_io.do_not_reverse_lookup = flag
-
end
-
end
-
-
1
module Nonblock
-
1
def initialize(*args)
-
flag = File::NONBLOCK
-
flag |= @io.fcntl(Fcntl::F_GETFL) if defined?(Fcntl::F_GETFL)
-
@io.fcntl(Fcntl::F_SETFL, flag)
-
super
-
end
-
end
-
-
1
def verify_certificate_identity(cert, hostname)
-
should_verify_common_name = true
-
cert.extensions.each{|ext|
-
next if ext.oid != "subjectAltName"
-
ext.value.split(/,\s+/).each{|general_name|
-
if /\ADNS:(.*)/ =~ general_name
-
should_verify_common_name = false
-
reg = Regexp.escape($1).gsub(/\\\*/, "[^.]+")
-
return true if /\A#{reg}\z/i =~ hostname
-
elsif /\AIP Address:(.*)/ =~ general_name
-
should_verify_common_name = false
-
return true if $1 == hostname
-
end
-
}
-
}
-
if should_verify_common_name
-
cert.subject.to_a.each{|oid, value|
-
if oid == "CN"
-
reg = Regexp.escape(value).gsub(/\\\*/, "[^.]+")
-
return true if /\A#{reg}\z/i =~ hostname
-
end
-
}
-
end
-
return false
-
end
-
1
module_function :verify_certificate_identity
-
-
1
class SSLSocket
-
1
include Buffering
-
1
include SocketForwarder
-
1
include Nonblock
-
-
1
def post_connection_check(hostname)
-
unless OpenSSL::SSL.verify_certificate_identity(peer_cert, hostname)
-
raise SSLError, "hostname does not match the server certificate"
-
end
-
return true
-
end
-
-
1
def session
-
SSL::Session.new(self)
-
rescue SSL::Session::SessionError
-
nil
-
end
-
end
-
-
1
class SSLServer
-
1
include SocketForwarder
-
1
attr_accessor :start_immediately
-
-
1
def initialize(svr, ctx)
-
@svr = svr
-
@ctx = ctx
-
unless ctx.session_id_context
-
session_id = OpenSSL::Digest::MD5.hexdigest($0)
-
@ctx.session_id_context = session_id
-
end
-
@start_immediately = true
-
end
-
-
1
def to_io
-
@svr
-
end
-
-
1
def listen(backlog=5)
-
@svr.listen(backlog)
-
end
-
-
1
def shutdown(how=Socket::SHUT_RDWR)
-
@svr.shutdown(how)
-
end
-
-
1
def accept
-
sock = @svr.accept
-
begin
-
ssl = OpenSSL::SSL::SSLSocket.new(sock, @ctx)
-
ssl.sync_close = true
-
ssl.accept if @start_immediately
-
ssl
-
rescue SSLError => ex
-
sock.close
-
raise ex
-
end
-
end
-
-
1
def close
-
@svr.close
-
end
-
end
-
end
-
end
-
=begin
-
= $RCSfile$ -- Ruby-space definitions that completes C-space funcs for X509 and subclasses
-
-
= Info
-
'OpenSSL for Ruby 2' project
-
Copyright (C) 2002 Michal Rokos <m.rokos@sh.cvut.cz>
-
All rights reserved.
-
-
= Licence
-
This program is licenced under the same licence as Ruby.
-
(See the file 'LICENCE'.)
-
-
= Version
-
$Id: x509-internal.rb 32663 2011-07-25 04:51:26Z nahi $
-
=end
-
-
1
module OpenSSL
-
1
module X509
-
1
class ExtensionFactory
-
1
def create_extension(*arg)
-
if arg.size > 1
-
create_ext(*arg)
-
else
-
send("create_ext_from_"+arg[0].class.name.downcase, arg[0])
-
end
-
end
-
-
1
def create_ext_from_array(ary)
-
raise ExtensionError, "unexpected array form" if ary.size > 3
-
create_ext(ary[0], ary[1], ary[2])
-
end
-
-
1
def create_ext_from_string(str) # "oid = critical, value"
-
oid, value = str.split(/=/, 2)
-
oid.strip!
-
value.strip!
-
create_ext(oid, value)
-
end
-
-
1
def create_ext_from_hash(hash)
-
create_ext(hash["oid"], hash["value"], hash["critical"])
-
end
-
end
-
-
1
class Extension
-
1
def to_s # "oid = critical, value"
-
str = self.oid
-
str << " = "
-
str << "critical, " if self.critical?
-
str << self.value.gsub(/\n/, ", ")
-
end
-
-
1
def to_h # {"oid"=>sn|ln, "value"=>value, "critical"=>true|false}
-
{"oid"=>self.oid,"value"=>self.value,"critical"=>self.critical?}
-
end
-
-
1
def to_a
-
[ self.oid, self.value, self.critical? ]
-
end
-
end
-
-
1
class Name
-
1
module RFC2253DN
-
1
Special = ',=+<>#;'
-
1
HexChar = /[0-9a-fA-F]/
-
1
HexPair = /#{HexChar}#{HexChar}/
-
1
HexString = /#{HexPair}+/
-
1
Pair = /\\(?:[#{Special}]|\\|"|#{HexPair})/
-
1
StringChar = /[^#{Special}\\"]/
-
1
QuoteChar = /[^\\"]/
-
1
AttributeType = /[a-zA-Z][0-9a-zA-Z]*|[0-9]+(?:\.[0-9]+)*/
-
1
AttributeValue = /
-
(?!["#])((?:#{StringChar}|#{Pair})*)|
-
\#(#{HexString})|
-
"((?:#{QuoteChar}|#{Pair})*)"
-
/x
-
1
TypeAndValue = /\A(#{AttributeType})=#{AttributeValue}/
-
-
1
module_function
-
-
1
def expand_pair(str)
-
return nil unless str
-
return str.gsub(Pair){
-
pair = $&
-
case pair.size
-
when 2 then pair[1,1]
-
when 3 then Integer("0x#{pair[1,2]}").chr
-
else raise OpenSSL::X509::NameError, "invalid pair: #{str}"
-
end
-
}
-
end
-
-
1
def expand_hexstring(str)
-
return nil unless str
-
der = str.gsub(HexPair){$&.to_i(16).chr }
-
a1 = OpenSSL::ASN1.decode(der)
-
return a1.value, a1.tag
-
end
-
-
1
def expand_value(str1, str2, str3)
-
value = expand_pair(str1)
-
value, tag = expand_hexstring(str2) unless value
-
value = expand_pair(str3) unless value
-
return value, tag
-
end
-
-
1
def scan(dn)
-
str = dn
-
ary = []
-
while true
-
if md = TypeAndValue.match(str)
-
remain = md.post_match
-
type = md[1]
-
value, tag = expand_value(md[2], md[3], md[4]) rescue nil
-
if value
-
type_and_value = [type, value]
-
type_and_value.push(tag) if tag
-
ary.unshift(type_and_value)
-
if remain.length > 2 && remain[0] == ?,
-
str = remain[1..-1]
-
next
-
elsif remain.length > 2 && remain[0] == ?+
-
raise OpenSSL::X509::NameError,
-
"multi-valued RDN is not supported: #{dn}"
-
elsif remain.empty?
-
break
-
end
-
end
-
end
-
msg_dn = dn[0, dn.length - str.length] + " =>" + str
-
raise OpenSSL::X509::NameError, "malformed RDN: #{msg_dn}"
-
end
-
return ary
-
end
-
end
-
-
1
class << self
-
1
def parse_rfc2253(str, template=OBJECT_TYPE_TEMPLATE)
-
ary = OpenSSL::X509::Name::RFC2253DN.scan(str)
-
self.new(ary, template)
-
end
-
-
1
def parse_openssl(str, template=OBJECT_TYPE_TEMPLATE)
-
ary = str.scan(/\s*([^\/,]+)\s*/).collect{|i| i[0].split("=", 2) }
-
self.new(ary, template)
-
end
-
-
1
alias parse parse_openssl
-
end
-
end
-
-
1
class StoreContext
-
1
def cleanup
-
warn "(#{caller.first}) OpenSSL::X509::StoreContext#cleanup is deprecated with no replacement" if $VERBOSE
-
end
-
end
-
end
-
end
-
# == Pretty-printer for Ruby objects.
-
#
-
# = Which seems better?
-
#
-
# non-pretty-printed output by #p is:
-
# #<PP:0x81fedf0 @genspace=#<Proc:0x81feda0>, @group_queue=#<PrettyPrint::GroupQueue:0x81fed3c @queue=[[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], []]>, @buffer=[], @newline="\n", @group_stack=[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], @buffer_width=0, @indent=0, @maxwidth=79, @output_width=2, @output=#<IO:0x8114ee4>>
-
#
-
# pretty-printed output by #pp is:
-
# #<PP:0x81fedf0
-
# @buffer=[],
-
# @buffer_width=0,
-
# @genspace=#<Proc:0x81feda0>,
-
# @group_queue=
-
# #<PrettyPrint::GroupQueue:0x81fed3c
-
# @queue=
-
# [[#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
-
# []]>,
-
# @group_stack=
-
# [#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
-
# @indent=0,
-
# @maxwidth=79,
-
# @newline="\n",
-
# @output=#<IO:0x8114ee4>,
-
# @output_width=2>
-
#
-
# I like the latter. If you do too, this library is for you.
-
#
-
# = Usage
-
#
-
# pp(obj)
-
#
-
# output +obj+ to +$>+ in pretty printed format.
-
#
-
# It returns +nil+.
-
#
-
# = Output Customization
-
# To define your customized pretty printing function for your classes,
-
# redefine a method #pretty_print(+pp+) in the class.
-
# It takes an argument +pp+ which is an instance of the class PP.
-
# The method should use PP#text, PP#breakable, PP#nest, PP#group and
-
# PP#pp to print the object.
-
#
-
# = Author
-
# Tanaka Akira <akr@m17n.org>
-
-
1
require 'prettyprint'
-
-
1
module Kernel
-
# returns a pretty printed object as a string.
-
1
def pretty_inspect
-
PP.pp(self, '')
-
end
-
-
1
private
-
# prints arguments in pretty form.
-
#
-
# pp returns argument(s).
-
1
def pp(*objs) # :doc:
-
objs.each {|obj|
-
PP.pp(obj)
-
}
-
objs.size <= 1 ? objs.first : objs
-
end
-
1
module_function :pp
-
end
-
-
1
class PP < PrettyPrint
-
# Outputs +obj+ to +out+ in pretty printed format of
-
# +width+ columns in width.
-
#
-
# If +out+ is omitted, +$>+ is assumed.
-
# If +width+ is omitted, 79 is assumed.
-
#
-
# PP.pp returns +out+.
-
1
def PP.pp(obj, out=$>, width=79)
-
q = PP.new(out, width)
-
q.guard_inspect_key {q.pp obj}
-
q.flush
-
#$pp = q
-
out << "\n"
-
end
-
-
# Outputs +obj+ to +out+ like PP.pp but with no indent and
-
# newline.
-
#
-
# PP.singleline_pp returns +out+.
-
1
def PP.singleline_pp(obj, out=$>)
-
q = SingleLine.new(out)
-
q.guard_inspect_key {q.pp obj}
-
q.flush
-
out
-
end
-
-
# :stopdoc:
-
1
def PP.mcall(obj, mod, meth, *args, &block)
-
mod.instance_method(meth).bind(obj).call(*args, &block)
-
end
-
# :startdoc:
-
-
1
@sharing_detection = false
-
1
class << self
-
# Returns the sharing detection flag as a boolean value.
-
# It is false by default.
-
1
attr_accessor :sharing_detection
-
end
-
-
1
module PPMethods
-
1
def guard_inspect_key
-
if Thread.current[:__recursive_key__] == nil
-
Thread.current[:__recursive_key__] = {}.untrust
-
end
-
-
if Thread.current[:__recursive_key__][:inspect] == nil
-
Thread.current[:__recursive_key__][:inspect] = {}.untrust
-
end
-
-
save = Thread.current[:__recursive_key__][:inspect]
-
-
begin
-
Thread.current[:__recursive_key__][:inspect] = {}.untrust
-
yield
-
ensure
-
Thread.current[:__recursive_key__][:inspect] = save
-
end
-
end
-
-
1
def check_inspect_key(id)
-
Thread.current[:__recursive_key__] &&
-
Thread.current[:__recursive_key__][:inspect] &&
-
Thread.current[:__recursive_key__][:inspect].include?(id)
-
end
-
1
def push_inspect_key(id)
-
Thread.current[:__recursive_key__][:inspect][id] = true
-
end
-
1
def pop_inspect_key(id)
-
Thread.current[:__recursive_key__][:inspect].delete id
-
end
-
-
# Adds +obj+ to the pretty printing buffer
-
# using Object#pretty_print or Object#pretty_print_cycle.
-
#
-
# Object#pretty_print_cycle is used when +obj+ is already
-
# printed, a.k.a the object reference chain has a cycle.
-
1
def pp(obj)
-
id = obj.object_id
-
-
if check_inspect_key(id)
-
group {obj.pretty_print_cycle self}
-
return
-
end
-
-
begin
-
push_inspect_key(id)
-
group {obj.pretty_print self}
-
ensure
-
pop_inspect_key(id) unless PP.sharing_detection
-
end
-
end
-
-
# A convenience method which is same as follows:
-
#
-
# group(1, '#<' + obj.class.name, '>') { ... }
-
1
def object_group(obj, &block) # :yield:
-
group(1, '#<' + obj.class.name, '>', &block)
-
end
-
-
1
PointerMask = (1 << ([""].pack("p").size * 8)) - 1
-
-
1
case Object.new.inspect
-
when /\A\#<Object:0x([0-9a-f]+)>\z/
-
1
PointerFormat = "%0#{$1.length}x"
-
else
-
PointerFormat = "%x"
-
end
-
-
1
def object_address_group(obj, &block)
-
id = PointerFormat % (obj.object_id * 2 & PointerMask)
-
group(1, "\#<#{obj.class}:0x#{id}", '>', &block)
-
end
-
-
# A convenience method which is same as follows:
-
#
-
# text ','
-
# breakable
-
1
def comma_breakable
-
text ','
-
breakable
-
end
-
-
# Adds a separated list.
-
# The list is separated by comma with breakable space, by default.
-
#
-
# #seplist iterates the +list+ using +iter_method+.
-
# It yields each object to the block given for #seplist.
-
# The procedure +separator_proc+ is called between each yields.
-
#
-
# If the iteration is zero times, +separator_proc+ is not called at all.
-
#
-
# If +separator_proc+ is nil or not given,
-
# +lambda { comma_breakable }+ is used.
-
# If +iter_method+ is not given, :each is used.
-
#
-
# For example, following 3 code fragments has similar effect.
-
#
-
# q.seplist([1,2,3]) {|v| xxx v }
-
#
-
# q.seplist([1,2,3], lambda { q.comma_breakable }, :each) {|v| xxx v }
-
#
-
# xxx 1
-
# q.comma_breakable
-
# xxx 2
-
# q.comma_breakable
-
# xxx 3
-
1
def seplist(list, sep=nil, iter_method=:each) # :yield: element
-
sep ||= lambda { comma_breakable }
-
first = true
-
list.__send__(iter_method) {|*v|
-
if first
-
first = false
-
else
-
sep.call
-
end
-
yield(*v)
-
}
-
end
-
-
1
def pp_object(obj)
-
object_address_group(obj) {
-
seplist(obj.pretty_print_instance_variables, lambda { text ',' }) {|v|
-
breakable
-
v = v.to_s if Symbol === v
-
text v
-
text '='
-
group(1) {
-
breakable ''
-
pp(obj.instance_eval(v))
-
}
-
}
-
}
-
end
-
-
1
def pp_hash(obj)
-
group(1, '{', '}') {
-
seplist(obj, nil, :each_pair) {|k, v|
-
group {
-
pp k
-
text '=>'
-
group(1) {
-
breakable ''
-
pp v
-
}
-
}
-
}
-
}
-
end
-
end
-
-
1
include PPMethods
-
-
1
class SingleLine < PrettyPrint::SingleLine
-
1
include PPMethods
-
end
-
-
1
module ObjectMixin
-
# 1. specific pretty_print
-
# 2. specific inspect
-
# 3. specific to_s
-
# 4. generic pretty_print
-
-
# A default pretty printing method for general objects.
-
# It calls #pretty_print_instance_variables to list instance variables.
-
#
-
# If +self+ has a customized (redefined) #inspect method,
-
# the result of self.inspect is used but it obviously has no
-
# line break hints.
-
#
-
# This module provides predefined #pretty_print methods for some of
-
# the most commonly used built-in classes for convenience.
-
1
def pretty_print(q)
-
method_method = Object.instance_method(:method).bind(self)
-
begin
-
inspect_method = method_method.call(:inspect)
-
rescue NameError
-
end
-
begin
-
to_s_method = method_method.call(:to_s)
-
rescue NameError
-
end
-
if inspect_method && /\(Kernel\)#/ !~ inspect_method.inspect
-
q.text self.inspect
-
elsif !inspect_method && self.respond_to?(:inspect)
-
q.text self.inspect
-
elsif to_s_method && /\(Kernel\)#/ !~ to_s_method.inspect
-
q.text self.to_s
-
elsif !to_s_method && self.respond_to?(:to_s)
-
q.text self.to_s
-
else
-
q.pp_object(self)
-
end
-
end
-
-
# A default pretty printing method for general objects that are
-
# detected as part of a cycle.
-
1
def pretty_print_cycle(q)
-
q.object_address_group(self) {
-
q.breakable
-
q.text '...'
-
}
-
end
-
-
# Returns a sorted array of instance variable names.
-
#
-
# This method should return an array of names of instance variables as symbols or strings as:
-
# +[:@a, :@b]+.
-
1
def pretty_print_instance_variables
-
instance_variables.sort
-
end
-
-
# Is #inspect implementation using #pretty_print.
-
# If you implement #pretty_print, it can be used as follows.
-
#
-
# alias inspect pretty_print_inspect
-
#
-
# However, doing this requires that every class that #inspect is called on
-
# implement #pretty_print, or a RuntimeError will be raised.
-
1
def pretty_print_inspect
-
if /\(PP::ObjectMixin\)#/ =~ Object.instance_method(:method).bind(self).call(:pretty_print).inspect
-
raise "pretty_print is not overridden for #{self.class}"
-
end
-
PP.singleline_pp(self, '')
-
end
-
end
-
end
-
-
1
class Array
-
1
def pretty_print(q)
-
q.group(1, '[', ']') {
-
q.seplist(self) {|v|
-
q.pp v
-
}
-
}
-
end
-
-
1
def pretty_print_cycle(q)
-
q.text(empty? ? '[]' : '[...]')
-
end
-
end
-
-
1
class Hash
-
1
def pretty_print(q)
-
q.pp_hash self
-
end
-
-
1
def pretty_print_cycle(q)
-
q.text(empty? ? '{}' : '{...}')
-
end
-
end
-
-
1
class << ENV
-
1
def pretty_print(q)
-
h = {}
-
ENV.keys.sort.each {|k|
-
h[k] = ENV[k]
-
}
-
q.pp_hash h
-
end
-
end
-
-
1
class Struct
-
1
def pretty_print(q)
-
q.group(1, sprintf("#<struct %s", PP.mcall(self, Kernel, :class).name), '>') {
-
q.seplist(PP.mcall(self, Struct, :members), lambda { q.text "," }) {|member|
-
q.breakable
-
q.text member.to_s
-
q.text '='
-
q.group(1) {
-
q.breakable ''
-
q.pp self[member]
-
}
-
}
-
}
-
end
-
-
1
def pretty_print_cycle(q)
-
q.text sprintf("#<struct %s:...>", PP.mcall(self, Kernel, :class).name)
-
end
-
end
-
-
1
class Range
-
1
def pretty_print(q)
-
q.pp self.begin
-
q.breakable ''
-
q.text(self.exclude_end? ? '...' : '..')
-
q.breakable ''
-
q.pp self.end
-
end
-
end
-
-
1
class File < IO
-
1
class Stat
-
1
def pretty_print(q)
-
require 'etc.so'
-
q.object_group(self) {
-
q.breakable
-
q.text sprintf("dev=0x%x", self.dev); q.comma_breakable
-
q.text "ino="; q.pp self.ino; q.comma_breakable
-
q.group {
-
m = self.mode
-
q.text sprintf("mode=0%o", m)
-
q.breakable
-
q.text sprintf("(%s %c%c%c%c%c%c%c%c%c)",
-
self.ftype,
-
(m & 0400 == 0 ? ?- : ?r),
-
(m & 0200 == 0 ? ?- : ?w),
-
(m & 0100 == 0 ? (m & 04000 == 0 ? ?- : ?S) :
-
(m & 04000 == 0 ? ?x : ?s)),
-
(m & 0040 == 0 ? ?- : ?r),
-
(m & 0020 == 0 ? ?- : ?w),
-
(m & 0010 == 0 ? (m & 02000 == 0 ? ?- : ?S) :
-
(m & 02000 == 0 ? ?x : ?s)),
-
(m & 0004 == 0 ? ?- : ?r),
-
(m & 0002 == 0 ? ?- : ?w),
-
(m & 0001 == 0 ? (m & 01000 == 0 ? ?- : ?T) :
-
(m & 01000 == 0 ? ?x : ?t)))
-
}
-
q.comma_breakable
-
q.text "nlink="; q.pp self.nlink; q.comma_breakable
-
q.group {
-
q.text "uid="; q.pp self.uid
-
begin
-
pw = Etc.getpwuid(self.uid)
-
rescue ArgumentError
-
end
-
if pw
-
q.breakable; q.text "(#{pw.name})"
-
end
-
}
-
q.comma_breakable
-
q.group {
-
q.text "gid="; q.pp self.gid
-
begin
-
gr = Etc.getgrgid(self.gid)
-
rescue ArgumentError
-
end
-
if gr
-
q.breakable; q.text "(#{gr.name})"
-
end
-
}
-
q.comma_breakable
-
q.group {
-
q.text sprintf("rdev=0x%x", self.rdev)
-
q.breakable
-
q.text sprintf('(%d, %d)', self.rdev_major, self.rdev_minor)
-
}
-
q.comma_breakable
-
q.text "size="; q.pp self.size; q.comma_breakable
-
q.text "blksize="; q.pp self.blksize; q.comma_breakable
-
q.text "blocks="; q.pp self.blocks; q.comma_breakable
-
q.group {
-
t = self.atime
-
q.text "atime="; q.pp t
-
q.breakable; q.text "(#{t.tv_sec})"
-
}
-
q.comma_breakable
-
q.group {
-
t = self.mtime
-
q.text "mtime="; q.pp t
-
q.breakable; q.text "(#{t.tv_sec})"
-
}
-
q.comma_breakable
-
q.group {
-
t = self.ctime
-
q.text "ctime="; q.pp t
-
q.breakable; q.text "(#{t.tv_sec})"
-
}
-
}
-
end
-
end
-
end
-
-
1
class MatchData
-
1
def pretty_print(q)
-
nc = []
-
self.regexp.named_captures.each {|name, indexes|
-
indexes.each {|i| nc[i] = name }
-
}
-
q.object_group(self) {
-
q.breakable
-
q.seplist(0...self.size, lambda { q.breakable }) {|i|
-
if i == 0
-
q.pp self[i]
-
else
-
if nc[i]
-
q.text nc[i]
-
else
-
q.pp i
-
end
-
q.text ':'
-
q.pp self[i]
-
end
-
}
-
}
-
end
-
end
-
-
1
class Object < BasicObject
-
1
include PP::ObjectMixin
-
end
-
-
1
[Numeric, Symbol, FalseClass, TrueClass, NilClass, Module].each {|c|
-
6
c.class_eval {
-
6
def pretty_print_cycle(q)
-
q.text inspect
-
end
-
}
-
}
-
-
1
[Numeric, FalseClass, TrueClass, Module].each {|c|
-
4
c.class_eval {
-
4
def pretty_print(q)
-
q.text inspect
-
end
-
}
-
}
-
# This class implements a pretty printing algorithm. It finds line breaks and
-
# nice indentations for grouped structure.
-
#
-
# By default, the class assumes that primitive elements are strings and each
-
# byte in the strings have single column in width. But it can be used for
-
# other situations by giving suitable arguments for some methods:
-
# * newline object and space generation block for PrettyPrint.new
-
# * optional width argument for PrettyPrint#text
-
# * PrettyPrint#breakable
-
#
-
# There are several candidate uses:
-
# * text formatting using proportional fonts
-
# * multibyte characters which has columns different to number of bytes
-
# * non-string formatting
-
#
-
# == Bugs
-
# * Box based formatting?
-
# * Other (better) model/algorithm?
-
#
-
# == References
-
# Christian Lindig, Strictly Pretty, March 2000,
-
# http://www.st.cs.uni-sb.de/~lindig/papers/#pretty
-
#
-
# Philip Wadler, A prettier printer, March 1998,
-
# http://homepages.inf.ed.ac.uk/wadler/topics/language-design.html#prettier
-
#
-
# == Author
-
# Tanaka Akira <akr@m17n.org>
-
#
-
1
class PrettyPrint
-
-
# This is a convenience method which is same as follows:
-
#
-
# begin
-
# q = PrettyPrint.new(output, maxwidth, newline, &genspace)
-
# ...
-
# q.flush
-
# output
-
# end
-
#
-
1
def PrettyPrint.format(output='', maxwidth=79, newline="\n", genspace=lambda {|n| ' ' * n})
-
q = PrettyPrint.new(output, maxwidth, newline, &genspace)
-
yield q
-
q.flush
-
output
-
end
-
-
# This is similar to PrettyPrint::format but the result has no breaks.
-
#
-
# +maxwidth+, +newline+ and +genspace+ are ignored.
-
#
-
# The invocation of +breakable+ in the block doesn't break a line and is
-
# treated as just an invocation of +text+.
-
#
-
1
def PrettyPrint.singleline_format(output='', maxwidth=nil, newline=nil, genspace=nil)
-
q = SingleLine.new(output)
-
yield q
-
output
-
end
-
-
# Creates a buffer for pretty printing.
-
#
-
# +output+ is an output target. If it is not specified, '' is assumed. It
-
# should have a << method which accepts the first argument +obj+ of
-
# PrettyPrint#text, the first argument +sep+ of PrettyPrint#breakable, the
-
# first argument +newline+ of PrettyPrint.new, and the result of a given
-
# block for PrettyPrint.new.
-
#
-
# +maxwidth+ specifies maximum line length. If it is not specified, 79 is
-
# assumed. However actual outputs may overflow +maxwidth+ if long
-
# non-breakable texts are provided.
-
#
-
# +newline+ is used for line breaks. "\n" is used if it is not specified.
-
#
-
# The block is used to generate spaces. {|width| ' ' * width} is used if it
-
# is not given.
-
#
-
1
def initialize(output='', maxwidth=79, newline="\n", &genspace)
-
@output = output
-
@maxwidth = maxwidth
-
@newline = newline
-
@genspace = genspace || lambda {|n| ' ' * n}
-
-
@output_width = 0
-
@buffer_width = 0
-
@buffer = []
-
-
root_group = Group.new(0)
-
@group_stack = [root_group]
-
@group_queue = GroupQueue.new(root_group)
-
@indent = 0
-
end
-
1
attr_reader :output, :maxwidth, :newline, :genspace
-
1
attr_reader :indent, :group_queue
-
-
# Returns the group most recently added to the stack.
-
1
def current_group
-
@group_stack.last
-
end
-
-
# first? is a predicate to test the call is a first call to first? with
-
# current group.
-
#
-
# It is useful to format comma separated values as:
-
#
-
# q.group(1, '[', ']') {
-
# xxx.each {|yyy|
-
# unless q.first?
-
# q.text ','
-
# q.breakable
-
# end
-
# ... pretty printing yyy ...
-
# }
-
# }
-
#
-
# first? is obsoleted in 1.8.2.
-
#
-
1
def first?
-
warn "PrettyPrint#first? is obsoleted at 1.8.2."
-
current_group.first?
-
end
-
-
# Breaks the buffer into lines that are shorter than #maxwidth
-
1
def break_outmost_groups
-
while @maxwidth < @output_width + @buffer_width
-
return unless group = @group_queue.deq
-
until group.breakables.empty?
-
data = @buffer.shift
-
@output_width = data.output(@output, @output_width)
-
@buffer_width -= data.width
-
end
-
while !@buffer.empty? && Text === @buffer.first
-
text = @buffer.shift
-
@output_width = text.output(@output, @output_width)
-
@buffer_width -= text.width
-
end
-
end
-
end
-
-
# This adds +obj+ as a text of +width+ columns in width.
-
#
-
# If +width+ is not specified, obj.length is used.
-
#
-
1
def text(obj, width=obj.length)
-
if @buffer.empty?
-
@output << obj
-
@output_width += width
-
else
-
text = @buffer.last
-
unless Text === text
-
text = Text.new
-
@buffer << text
-
end
-
text.add(obj, width)
-
@buffer_width += width
-
break_outmost_groups
-
end
-
end
-
-
# This is similar to #breakable except
-
# the decision to break or not is determined individually.
-
#
-
# Two #fill_breakable under a group may cause 4 results:
-
# (break,break), (break,non-break), (non-break,break), (non-break,non-break).
-
# This is different to #breakable because two #breakable under a group
-
# may cause 2 results:
-
# (break,break), (non-break,non-break).
-
#
-
# The text sep+ is inserted if a line is not broken at this point.
-
#
-
# If +sep+ is not specified, " " is used.
-
#
-
# If +width+ is not specified, +sep.length+ is used. You will have to
-
# specify this when +sep+ is a multibyte character, for example.
-
#
-
1
def fill_breakable(sep=' ', width=sep.length)
-
group { breakable sep, width }
-
end
-
-
# This says "you can break a line here if necessary", and a +width+\-column
-
# text +sep+ is inserted if a line is not broken at the point.
-
#
-
# If +sep+ is not specified, " " is used.
-
#
-
# If +width+ is not specified, +sep.length+ is used. You will have to
-
# specify this when +sep+ is a multibyte character, for example.
-
#
-
1
def breakable(sep=' ', width=sep.length)
-
group = @group_stack.last
-
if group.break?
-
flush
-
@output << @newline
-
@output << @genspace.call(@indent)
-
@output_width = @indent
-
@buffer_width = 0
-
else
-
@buffer << Breakable.new(sep, width, self)
-
@buffer_width += width
-
break_outmost_groups
-
end
-
end
-
-
# Groups line break hints added in the block. The line break hints are all
-
# to be used or not.
-
#
-
# If +indent+ is specified, the method call is regarded as nested by
-
# nest(indent) { ... }.
-
#
-
# If +open_obj+ is specified, <tt>text open_obj, open_width</tt> is called
-
# before grouping. If +close_obj+ is specified, <tt>text close_obj,
-
# close_width</tt> is called after grouping.
-
#
-
1
def group(indent=0, open_obj='', close_obj='', open_width=open_obj.length, close_width=close_obj.length)
-
text open_obj, open_width
-
group_sub {
-
nest(indent) {
-
yield
-
}
-
}
-
text close_obj, close_width
-
end
-
-
1
def group_sub
-
group = Group.new(@group_stack.last.depth + 1)
-
@group_stack.push group
-
@group_queue.enq group
-
begin
-
yield
-
ensure
-
@group_stack.pop
-
if group.breakables.empty?
-
@group_queue.delete group
-
end
-
end
-
end
-
-
# Increases left margin after newline with +indent+ for line breaks added in
-
# the block.
-
#
-
1
def nest(indent)
-
@indent += indent
-
begin
-
yield
-
ensure
-
@indent -= indent
-
end
-
end
-
-
# outputs buffered data.
-
#
-
1
def flush
-
@buffer.each {|data|
-
@output_width = data.output(@output, @output_width)
-
}
-
@buffer.clear
-
@buffer_width = 0
-
end
-
-
1
class Text
-
1
def initialize
-
@objs = []
-
@width = 0
-
end
-
1
attr_reader :width
-
-
1
def output(out, output_width)
-
@objs.each {|obj| out << obj}
-
output_width + @width
-
end
-
-
1
def add(obj, width)
-
@objs << obj
-
@width += width
-
end
-
end
-
-
1
class Breakable
-
1
def initialize(sep, width, q)
-
@obj = sep
-
@width = width
-
@pp = q
-
@indent = q.indent
-
@group = q.current_group
-
@group.breakables.push self
-
end
-
1
attr_reader :obj, :width, :indent
-
-
1
def output(out, output_width)
-
@group.breakables.shift
-
if @group.break?
-
out << @pp.newline
-
out << @pp.genspace.call(@indent)
-
@indent
-
else
-
@pp.group_queue.delete @group if @group.breakables.empty?
-
out << @obj
-
output_width + @width
-
end
-
end
-
end
-
-
1
class Group
-
1
def initialize(depth)
-
@depth = depth
-
@breakables = []
-
@break = false
-
end
-
1
attr_reader :depth, :breakables
-
-
1
def break
-
@break = true
-
end
-
-
1
def break?
-
@break
-
end
-
-
1
def first?
-
if defined? @first
-
false
-
else
-
@first = false
-
true
-
end
-
end
-
end
-
-
1
class GroupQueue
-
1
def initialize(*groups)
-
@queue = []
-
groups.each {|g| enq g}
-
end
-
-
1
def enq(group)
-
depth = group.depth
-
@queue << [] until depth < @queue.length
-
@queue[depth] << group
-
end
-
-
1
def deq
-
@queue.each {|gs|
-
(gs.length-1).downto(0) {|i|
-
unless gs[i].breakables.empty?
-
group = gs.slice!(i, 1).first
-
group.break
-
return group
-
end
-
}
-
gs.each {|group| group.break}
-
gs.clear
-
}
-
return nil
-
end
-
-
1
def delete(group)
-
@queue[group.depth].delete(group)
-
end
-
end
-
-
1
class SingleLine
-
1
def initialize(output, maxwidth=nil, newline=nil)
-
@output = output
-
@first = [true]
-
end
-
-
1
def text(obj, width=nil)
-
@output << obj
-
end
-
-
1
def breakable(sep=' ', width=nil)
-
@output << sep
-
end
-
-
1
def nest(indent)
-
yield
-
end
-
-
1
def group(indent=nil, open_obj='', close_obj='', open_width=nil, close_width=nil)
-
@first.push true
-
@output << open_obj
-
yield
-
@output << close_obj
-
@first.pop
-
end
-
-
1
def flush
-
end
-
-
1
def first?
-
result = @first[-1]
-
@first[-1] = false
-
result
-
end
-
end
-
end
-
#
-
# $originalId: parser.rb,v 1.8 2006/07/06 11:42:07 aamine Exp $
-
#
-
# Copyright (c) 1999-2006 Minero Aoki
-
#
-
# This program is free software.
-
# You can distribute/modify this program under the same terms of ruby.
-
#
-
# As a special exception, when this code is copied by Racc
-
# into a Racc output file, you may use that output file
-
# without restriction.
-
#
-
-
1
unless defined?(NotImplementedError)
-
NotImplementedError = NotImplementError
-
end
-
-
1
module Racc
-
1
class ParseError < StandardError; end
-
end
-
1
unless defined?(::ParseError)
-
1
ParseError = Racc::ParseError
-
end
-
-
1
module Racc
-
-
1
unless defined?(Racc_No_Extentions)
-
1
Racc_No_Extentions = false
-
end
-
-
1
class Parser
-
-
1
Racc_Runtime_Version = '1.4.6'
-
1
Racc_Runtime_Revision = %w$originalRevision: 1.8 $[1]
-
-
1
Racc_Runtime_Core_Version_R = '1.4.6'
-
1
Racc_Runtime_Core_Revision_R = %w$originalRevision: 1.8 $[1]
-
1
begin
-
1
require 'racc/cparse'
-
# Racc_Runtime_Core_Version_C = (defined in extention)
-
1
Racc_Runtime_Core_Revision_C = Racc_Runtime_Core_Id_C.split[2]
-
1
unless new.respond_to?(:_racc_do_parse_c, true)
-
raise LoadError, 'old cparse.so'
-
end
-
1
if Racc_No_Extentions
-
raise LoadError, 'selecting ruby version of racc runtime core'
-
end
-
-
1
Racc_Main_Parsing_Routine = :_racc_do_parse_c
-
1
Racc_YY_Parse_Method = :_racc_yyparse_c
-
1
Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_C
-
1
Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_C
-
1
Racc_Runtime_Type = 'c'
-
rescue LoadError
-
Racc_Main_Parsing_Routine = :_racc_do_parse_rb
-
Racc_YY_Parse_Method = :_racc_yyparse_rb
-
Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_R
-
Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_R
-
Racc_Runtime_Type = 'ruby'
-
end
-
-
1
def Parser.racc_runtime_type
-
Racc_Runtime_Type
-
end
-
-
1
private
-
-
1
def _racc_setup
-
@yydebug = false unless self.class::Racc_debug_parser
-
@yydebug = false unless defined?(@yydebug)
-
if @yydebug
-
@racc_debug_out = $stderr unless defined?(@racc_debug_out)
-
@racc_debug_out ||= $stderr
-
end
-
arg = self.class::Racc_arg
-
arg[13] = true if arg.size < 14
-
arg
-
end
-
-
1
def _racc_init_sysvars
-
@racc_state = [0]
-
@racc_tstack = []
-
@racc_vstack = []
-
-
@racc_t = nil
-
@racc_val = nil
-
-
@racc_read_next = true
-
-
@racc_user_yyerror = false
-
@racc_error_status = 0
-
end
-
-
###
-
### do_parse
-
###
-
-
class_eval %{
-
def do_parse
-
#{Racc_Main_Parsing_Routine}(_racc_setup(), false)
-
end
-
1
}
-
-
1
def next_token
-
raise NotImplementedError, "#{self.class}\#next_token is not defined"
-
end
-
-
1
def _racc_do_parse_rb(arg, in_debug)
-
action_table, action_check, action_default, action_pointer,
-
_, _, _, _,
-
_, _, token_table, _,
-
_, _, * = arg
-
-
_racc_init_sysvars
-
tok = act = i = nil
-
-
catch(:racc_end_parse) {
-
while true
-
if i = action_pointer[@racc_state[-1]]
-
if @racc_read_next
-
if @racc_t != 0 # not EOF
-
tok, @racc_val = next_token()
-
unless tok # EOF
-
@racc_t = 0
-
else
-
@racc_t = (token_table[tok] or 1) # error token
-
end
-
racc_read_token(@racc_t, tok, @racc_val) if @yydebug
-
@racc_read_next = false
-
end
-
end
-
i += @racc_t
-
unless i >= 0 and
-
act = action_table[i] and
-
action_check[i] == @racc_state[-1]
-
act = action_default[@racc_state[-1]]
-
end
-
else
-
act = action_default[@racc_state[-1]]
-
end
-
while act = _racc_evalact(act, arg)
-
;
-
end
-
end
-
}
-
end
-
-
###
-
### yyparse
-
###
-
-
class_eval %{
-
def yyparse(recv, mid)
-
#{Racc_YY_Parse_Method}(recv, mid, _racc_setup(), true)
-
end
-
1
}
-
-
1
def _racc_yyparse_rb(recv, mid, arg, c_debug)
-
action_table, action_check, action_default, action_pointer,
-
_, _, _, _,
-
_, _, token_table, _,
-
_, _, * = arg
-
-
_racc_init_sysvars
-
act = nil
-
i = nil
-
-
catch(:racc_end_parse) {
-
until i = action_pointer[@racc_state[-1]]
-
while act = _racc_evalact(action_default[@racc_state[-1]], arg)
-
;
-
end
-
end
-
recv.__send__(mid) do |tok, val|
-
unless tok
-
@racc_t = 0
-
else
-
@racc_t = (token_table[tok] or 1) # error token
-
end
-
@racc_val = val
-
@racc_read_next = false
-
-
i += @racc_t
-
unless i >= 0 and
-
act = action_table[i] and
-
action_check[i] == @racc_state[-1]
-
act = action_default[@racc_state[-1]]
-
end
-
while act = _racc_evalact(act, arg)
-
;
-
end
-
-
while not(i = action_pointer[@racc_state[-1]]) or
-
not @racc_read_next or
-
@racc_t == 0 # $
-
unless i and i += @racc_t and
-
i >= 0 and
-
act = action_table[i] and
-
action_check[i] == @racc_state[-1]
-
act = action_default[@racc_state[-1]]
-
end
-
while act = _racc_evalact(act, arg)
-
;
-
end
-
end
-
end
-
}
-
end
-
-
###
-
### common
-
###
-
-
1
def _racc_evalact(act, arg)
-
action_table, action_check, _, action_pointer,
-
_, _, _, _,
-
_, _, _, shift_n, reduce_n,
-
_, _, * = arg
-
nerr = 0 # tmp
-
-
if act > 0 and act < shift_n
-
#
-
# shift
-
#
-
if @racc_error_status > 0
-
@racc_error_status -= 1 unless @racc_t == 1 # error token
-
end
-
@racc_vstack.push @racc_val
-
@racc_state.push act
-
@racc_read_next = true
-
if @yydebug
-
@racc_tstack.push @racc_t
-
racc_shift @racc_t, @racc_tstack, @racc_vstack
-
end
-
-
elsif act < 0 and act > -reduce_n
-
#
-
# reduce
-
#
-
code = catch(:racc_jump) {
-
@racc_state.push _racc_do_reduce(arg, act)
-
false
-
}
-
if code
-
case code
-
when 1 # yyerror
-
@racc_user_yyerror = true # user_yyerror
-
return -reduce_n
-
when 2 # yyaccept
-
return shift_n
-
else
-
raise '[Racc Bug] unknown jump code'
-
end
-
end
-
-
elsif act == shift_n
-
#
-
# accept
-
#
-
racc_accept if @yydebug
-
throw :racc_end_parse, @racc_vstack[0]
-
-
elsif act == -reduce_n
-
#
-
# error
-
#
-
case @racc_error_status
-
when 0
-
unless arg[21] # user_yyerror
-
nerr += 1
-
on_error @racc_t, @racc_val, @racc_vstack
-
end
-
when 3
-
if @racc_t == 0 # is $
-
throw :racc_end_parse, nil
-
end
-
@racc_read_next = true
-
end
-
@racc_user_yyerror = false
-
@racc_error_status = 3
-
while true
-
if i = action_pointer[@racc_state[-1]]
-
i += 1 # error token
-
if i >= 0 and
-
(act = action_table[i]) and
-
action_check[i] == @racc_state[-1]
-
break
-
end
-
end
-
throw :racc_end_parse, nil if @racc_state.size <= 1
-
@racc_state.pop
-
@racc_vstack.pop
-
if @yydebug
-
@racc_tstack.pop
-
racc_e_pop @racc_state, @racc_tstack, @racc_vstack
-
end
-
end
-
return act
-
-
else
-
raise "[Racc Bug] unknown action #{act.inspect}"
-
end
-
-
racc_next_state(@racc_state[-1], @racc_state) if @yydebug
-
-
nil
-
end
-
-
1
def _racc_do_reduce(arg, act)
-
_, _, _, _,
-
goto_table, goto_check, goto_default, goto_pointer,
-
nt_base, reduce_table, _, _,
-
_, use_result, * = arg
-
state = @racc_state
-
vstack = @racc_vstack
-
tstack = @racc_tstack
-
-
i = act * -3
-
len = reduce_table[i]
-
reduce_to = reduce_table[i+1]
-
method_id = reduce_table[i+2]
-
void_array = []
-
-
tmp_t = tstack[-len, len] if @yydebug
-
tmp_v = vstack[-len, len]
-
tstack[-len, len] = void_array if @yydebug
-
vstack[-len, len] = void_array
-
state[-len, len] = void_array
-
-
# tstack must be updated AFTER method call
-
if use_result
-
vstack.push __send__(method_id, tmp_v, vstack, tmp_v[0])
-
else
-
vstack.push __send__(method_id, tmp_v, vstack)
-
end
-
tstack.push reduce_to
-
-
racc_reduce(tmp_t, reduce_to, tstack, vstack) if @yydebug
-
-
k1 = reduce_to - nt_base
-
if i = goto_pointer[k1]
-
i += state[-1]
-
if i >= 0 and (curstate = goto_table[i]) and goto_check[i] == k1
-
return curstate
-
end
-
end
-
goto_default[k1]
-
end
-
-
1
def on_error(t, val, vstack)
-
raise ParseError, sprintf("\nparse error on value %s (%s)",
-
val.inspect, token_to_str(t) || '?')
-
end
-
-
1
def yyerror
-
throw :racc_jump, 1
-
end
-
-
1
def yyaccept
-
throw :racc_jump, 2
-
end
-
-
1
def yyerrok
-
@racc_error_status = 0
-
end
-
-
#
-
# for debugging output
-
#
-
-
1
def racc_read_token(t, tok, val)
-
@racc_debug_out.print 'read '
-
@racc_debug_out.print tok.inspect, '(', racc_token2str(t), ') '
-
@racc_debug_out.puts val.inspect
-
@racc_debug_out.puts
-
end
-
-
1
def racc_shift(tok, tstack, vstack)
-
@racc_debug_out.puts "shift #{racc_token2str tok}"
-
racc_print_stacks tstack, vstack
-
@racc_debug_out.puts
-
end
-
-
1
def racc_reduce(toks, sim, tstack, vstack)
-
out = @racc_debug_out
-
out.print 'reduce '
-
if toks.empty?
-
out.print ' <none>'
-
else
-
toks.each {|t| out.print ' ', racc_token2str(t) }
-
end
-
out.puts " --> #{racc_token2str(sim)}"
-
-
racc_print_stacks tstack, vstack
-
@racc_debug_out.puts
-
end
-
-
1
def racc_accept
-
@racc_debug_out.puts 'accept'
-
@racc_debug_out.puts
-
end
-
-
1
def racc_e_pop(state, tstack, vstack)
-
@racc_debug_out.puts 'error recovering mode: pop token'
-
racc_print_states state
-
racc_print_stacks tstack, vstack
-
@racc_debug_out.puts
-
end
-
-
1
def racc_next_state(curstate, state)
-
@racc_debug_out.puts "goto #{curstate}"
-
racc_print_states state
-
@racc_debug_out.puts
-
end
-
-
1
def racc_print_stacks(t, v)
-
out = @racc_debug_out
-
out.print ' ['
-
t.each_index do |i|
-
out.print ' (', racc_token2str(t[i]), ' ', v[i].inspect, ')'
-
end
-
out.puts ' ]'
-
end
-
-
1
def racc_print_states(s)
-
out = @racc_debug_out
-
out.print ' ['
-
s.each {|st| out.print ' ', st }
-
out.puts ' ]'
-
end
-
-
1
def racc_token2str(tok)
-
self.class::Racc_token_to_s_table[tok] or
-
raise "[Racc Bug] can't convert token #{tok} to string"
-
end
-
-
1
def token_to_str(t)
-
self.class::Racc_token_to_s_table[t]
-
end
-
-
end
-
-
end
-
#vim:ts=2 sw=2 noexpandtab:
-
1
require 'rexml/child'
-
1
require 'rexml/source'
-
-
1
module REXML
-
# This class needs:
-
# * Documentation
-
# * Work! Not all types of attlists are intelligently parsed, so we just
-
# spew back out what we get in. This works, but it would be better if
-
# we formatted the output ourselves.
-
#
-
# AttlistDecls provide *just* enough support to allow namespace
-
# declarations. If you need some sort of generalized support, or have an
-
# interesting idea about how to map the hideous, terrible design of DTD
-
# AttlistDecls onto an intuitive Ruby interface, let me know. I'm desperate
-
# for anything to make DTDs more palateable.
-
1
class AttlistDecl < Child
-
1
include Enumerable
-
-
# What is this? Got me.
-
1
attr_reader :element_name
-
-
# Create an AttlistDecl, pulling the information from a Source. Notice
-
# that this isn't very convenient; to create an AttlistDecl, you basically
-
# have to format it yourself, and then have the initializer parse it.
-
# Sorry, but for the forseeable future, DTD support in REXML is pretty
-
# weak on convenience. Have I mentioned how much I hate DTDs?
-
1
def initialize(source)
-
super()
-
if (source.kind_of? Array)
-
@element_name, @pairs, @contents = *source
-
end
-
end
-
-
# Access the attlist attribute/value pairs.
-
# value = attlist_decl[ attribute_name ]
-
1
def [](key)
-
@pairs[key]
-
end
-
-
# Whether an attlist declaration includes the given attribute definition
-
# if attlist_decl.include? "xmlns:foobar"
-
1
def include?(key)
-
@pairs.keys.include? key
-
end
-
-
# Iterate over the key/value pairs:
-
# attlist_decl.each { |attribute_name, attribute_value| ... }
-
1
def each(&block)
-
@pairs.each(&block)
-
end
-
-
# Write out exactly what we got in.
-
1
def write out, indent=-1
-
out << @contents
-
end
-
-
1
def node_type
-
:attlistdecl
-
end
-
end
-
end
-
1
require "rexml/namespace"
-
1
require 'rexml/text'
-
-
1
module REXML
-
# Defines an Element Attribute; IE, a attribute=value pair, as in:
-
# <element attribute="value"/>. Attributes can be in their own
-
# namespaces. General users of REXML will not interact with the
-
# Attribute class much.
-
1
class Attribute
-
1
include Node
-
1
include Namespace
-
-
# The element to which this attribute belongs
-
1
attr_reader :element
-
# The normalized value of this attribute. That is, the attribute with
-
# entities intact.
-
1
attr_writer :normalized
-
1
PATTERN = /\s*(#{NAME_STR})\s*=\s*(["'])(.*?)\2/um
-
-
1
NEEDS_A_SECOND_CHECK = /(<|&((#{Entity::NAME});|(#0*((?:\d+)|(?:x[a-fA-F0-9]+)));)?)/um
-
-
# Constructor.
-
# FIXME: The parser doesn't catch illegal characters in attributes
-
#
-
# first::
-
# Either: an Attribute, which this new attribute will become a
-
# clone of; or a String, which is the name of this attribute
-
# second::
-
# If +first+ is an Attribute, then this may be an Element, or nil.
-
# If nil, then the Element parent of this attribute is the parent
-
# of the +first+ Attribute. If the first argument is a String,
-
# then this must also be a String, and is the content of the attribute.
-
# If this is the content, it must be fully normalized (contain no
-
# illegal characters).
-
# parent::
-
# Ignored unless +first+ is a String; otherwise, may be the Element
-
# parent of this attribute, or nil.
-
#
-
#
-
# Attribute.new( attribute_to_clone )
-
# Attribute.new( attribute_to_clone, parent_element )
-
# Attribute.new( "attr", "attr_value" )
-
# Attribute.new( "attr", "attr_value", parent_element )
-
1
def initialize( first, second=nil, parent=nil )
-
103
@normalized = @unnormalized = @element = nil
-
103
if first.kind_of? Attribute
-
self.name = first.expanded_name
-
@unnormalized = first.value
-
if second.kind_of? Element
-
@element = second
-
else
-
@element = first.element
-
end
-
103
elsif first.kind_of? String
-
103
@element = parent
-
103
self.name = first
-
103
@normalized = second.to_s
-
else
-
raise "illegal argument #{first.class.name} to Attribute constructor"
-
end
-
end
-
-
# Returns the namespace of the attribute.
-
#
-
# e = Element.new( "elns:myelement" )
-
# e.add_attribute( "nsa:a", "aval" )
-
# e.add_attribute( "b", "bval" )
-
# e.attributes.get_attribute( "a" ).prefix # -> "nsa"
-
# e.attributes.get_attribute( "b" ).prefix # -> "elns"
-
# a = Attribute.new( "x", "y" )
-
# a.prefix # -> ""
-
1
def prefix
-
pf = super
-
if pf == ""
-
pf = @element.prefix if @element
-
end
-
pf
-
end
-
-
# Returns the namespace URL, if defined, or nil otherwise
-
#
-
# e = Element.new("el")
-
# e.add_attributes({"xmlns:ns", "http://url"})
-
# e.namespace( "ns" ) # -> "http://url"
-
1
def namespace arg=nil
-
arg = prefix if arg.nil?
-
@element.namespace arg
-
end
-
-
# Returns true if other is an Attribute and has the same name and value,
-
# false otherwise.
-
1
def ==( other )
-
other.kind_of?(Attribute) and other.name==name and other.value==value
-
end
-
-
# Creates (and returns) a hash from both the name and value
-
1
def hash
-
name.hash + value.hash
-
end
-
-
# Returns this attribute out as XML source, expanding the name
-
#
-
# a = Attribute.new( "x", "y" )
-
# a.to_string # -> "x='y'"
-
# b = Attribute.new( "ns:x", "y" )
-
# b.to_string # -> "ns:x='y'"
-
1
def to_string
-
if @element and @element.context and @element.context[:attribute_quote] == :quote
-
%Q^#@expanded_name="#{to_s().gsub(/"/, '"e;')}"^
-
else
-
"#@expanded_name='#{to_s().gsub(/'/, ''')}'"
-
end
-
end
-
-
1
def doctype
-
206
if @element
-
206
doc = @element.document
-
206
doc.doctype if doc
-
end
-
end
-
-
# Returns the attribute value, with entities replaced
-
1
def to_s
-
return @normalized if @normalized
-
-
@normalized = Text::normalize( @unnormalized, doctype )
-
@unnormalized = nil
-
@normalized
-
end
-
-
# Returns the UNNORMALIZED value of this attribute. That is, entities
-
# have been expanded to their values
-
1
def value
-
103
return @unnormalized if @unnormalized
-
103
@unnormalized = Text::unnormalize( @normalized, doctype )
-
103
@normalized = nil
-
103
@unnormalized
-
end
-
-
# Returns a copy of this attribute
-
1
def clone
-
Attribute.new self
-
end
-
-
# Sets the element of which this object is an attribute. Normally, this
-
# is not directly called.
-
#
-
# Returns this attribute
-
1
def element=( element )
-
103
@element = element
-
-
103
if @normalized
-
103
Text.check( @normalized, NEEDS_A_SECOND_CHECK, doctype )
-
end
-
-
103
self
-
end
-
-
# Removes this Attribute from the tree, and returns true if successfull
-
#
-
# This method is usually not called directly.
-
1
def remove
-
@element.attributes.delete self.name unless @element.nil?
-
end
-
-
# Writes this attribute (EG, puts 'key="value"' to the output)
-
1
def write( output, indent=-1 )
-
output << to_string
-
end
-
-
1
def node_type
-
:attribute
-
end
-
-
1
def inspect
-
rv = ""
-
write( rv )
-
rv
-
end
-
-
1
def xpath
-
path = @element.xpath
-
path += "/@#{self.expanded_name}"
-
return path
-
end
-
end
-
end
-
#vim:ts=2 sw=2 noexpandtab:
-
1
require "rexml/text"
-
-
1
module REXML
-
1
class CData < Text
-
1
START = '<![CDATA['
-
1
STOP = ']]>'
-
1
ILLEGAL = /(\]\]>)/
-
-
# Constructor. CData is data between <![CDATA[ ... ]]>
-
#
-
# _Examples_
-
# CData.new( source )
-
# CData.new( "Here is some CDATA" )
-
# CData.new( "Some unprocessed data", respect_whitespace_TF, parent_element )
-
1
def initialize( first, whitespace=true, parent=nil )
-
9
super( first, whitespace, parent, false, true, ILLEGAL )
-
end
-
-
# Make a copy of this object
-
#
-
# _Examples_
-
# c = CData.new( "Some text" )
-
# d = c.clone
-
# d.to_s # -> "Some text"
-
1
def clone
-
CData.new self
-
end
-
-
# Returns the content of this CData object
-
#
-
# _Examples_
-
# c = CData.new( "Some text" )
-
# c.to_s # -> "Some text"
-
1
def to_s
-
@string
-
end
-
-
1
def value
-
10
@string
-
end
-
-
# == DEPRECATED
-
# See the rexml/formatters package
-
#
-
# Generates XML output of this object
-
#
-
# output::
-
# Where to write the string. Defaults to $stdout
-
# indent::
-
# The amount to indent this node by
-
# transitive::
-
# Ignored
-
# ie_hack::
-
# Ignored
-
#
-
# _Examples_
-
# c = CData.new( " Some text " )
-
# c.write( $stdout ) #-> <![CDATA[ Some text ]]>
-
1
def write( output=$stdout, indent=-1, transitive=false, ie_hack=false )
-
Kernel.warn( "#{self.class.name}.write is deprecated" )
-
indent( output, indent )
-
output << START
-
output << @string
-
output << STOP
-
end
-
end
-
end
-
1
require "rexml/node"
-
-
1
module REXML
-
##
-
# A Child object is something contained by a parent, and this class
-
# contains methods to support that. Most user code will not use this
-
# class directly.
-
1
class Child
-
1
include Node
-
1
attr_reader :parent # The Parent of this object
-
-
# Constructor. Any inheritors of this class should call super to make
-
# sure this method is called.
-
# parent::
-
# if supplied, the parent of this child will be set to the
-
# supplied value, and self will be added to the parent
-
1
def initialize( parent = nil )
-
246
@parent = nil
-
# Declare @parent, but don't define it. The next line sets the
-
# parent.
-
246
parent.add( self ) if parent
-
end
-
-
# Replaces this object with another object. Basically, calls
-
# Parent.replace_child
-
#
-
# Returns:: self
-
1
def replace_with( child )
-
@parent.replace_child( self, child )
-
self
-
end
-
-
# Removes this child from the parent.
-
#
-
# Returns:: self
-
1
def remove
-
unless @parent.nil?
-
@parent.delete self
-
end
-
self
-
end
-
-
# Sets the parent of this child to the supplied argument.
-
#
-
# other::
-
# Must be a Parent object. If this object is the same object as the
-
# existing parent of this child, no action is taken. Otherwise, this
-
# child is removed from the current parent (if one exists), and is added
-
# to the new parent.
-
# Returns:: The parent added
-
1
def parent=( other )
-
574
return @parent if @parent == other
-
574
@parent.delete self if defined? @parent and @parent
-
574
@parent = other
-
end
-
-
1
alias :next_sibling :next_sibling_node
-
1
alias :previous_sibling :previous_sibling_node
-
-
# Sets the next sibling of this child. This can be used to insert a child
-
# after some other child.
-
# a = Element.new("a")
-
# b = a.add_element("b")
-
# c = Element.new("c")
-
# b.next_sibling = c
-
# # => <a><b/><c/></a>
-
1
def next_sibling=( other )
-
parent.insert_after self, other
-
end
-
-
# Sets the previous sibling of this child. This can be used to insert a
-
# child before some other child.
-
# a = Element.new("a")
-
# b = a.add_element("b")
-
# c = Element.new("c")
-
# b.previous_sibling = c
-
# # => <a><b/><c/></a>
-
1
def previous_sibling=(other)
-
parent.insert_before self, other
-
end
-
-
# Returns:: the document this child belongs to, or nil if this child
-
# belongs to no document
-
1
def document
-
40004
return parent.document unless parent.nil?
-
nil
-
end
-
-
# This doesn't yet handle encodings
-
1
def bytes
-
document.encoding
-
-
to_s
-
end
-
end
-
end
-
1
require "rexml/child"
-
-
1
module REXML
-
##
-
# Represents an XML comment; that is, text between \<!-- ... -->
-
1
class Comment < Child
-
1
include Comparable
-
1
START = "<!--"
-
1
STOP = "-->"
-
-
# The content text
-
-
1
attr_accessor :string
-
-
##
-
# Constructor. The first argument can be one of three types:
-
# @param first If String, the contents of this comment are set to the
-
# argument. If Comment, the argument is duplicated. If
-
# Source, the argument is scanned for a comment.
-
# @param second If the first argument is a Source, this argument
-
# should be nil, not supplied, or a Parent to be set as the parent
-
# of this object
-
1
def initialize( first, second = nil )
-
#puts "IN COMMENT CONSTRUCTOR; SECOND IS #{second.type}"
-
super(second)
-
if first.kind_of? String
-
@string = first
-
elsif first.kind_of? Comment
-
@string = first.string
-
end
-
end
-
-
1
def clone
-
Comment.new self
-
end
-
-
# == DEPRECATED
-
# See REXML::Formatters
-
#
-
# output::
-
# Where to write the string
-
# indent::
-
# An integer. If -1, no indenting will be used; otherwise, the
-
# indentation will be this number of spaces, and children will be
-
# indented an additional amount.
-
# transitive::
-
# Ignored by this class. The contents of comments are never modified.
-
# ie_hack::
-
# Needed for conformity to the child API, but not used by this class.
-
1
def write( output, indent=-1, transitive=false, ie_hack=false )
-
Kernel.warn("Comment.write is deprecated. See REXML::Formatters")
-
indent( output, indent )
-
output << START
-
output << @string
-
output << STOP
-
end
-
-
1
alias :to_s :string
-
-
##
-
# Compares this Comment to another; the contents of the comment are used
-
# in the comparison.
-
1
def <=>(other)
-
other.to_s <=> @string
-
end
-
-
##
-
# Compares this Comment to another; the contents of the comment are used
-
# in the comparison.
-
1
def ==( other )
-
other.kind_of? Comment and
-
(other <=> self) == 0
-
end
-
-
1
def node_type
-
:comment
-
end
-
end
-
end
-
#vim:ts=2 sw=2 noexpandtab:
-
1
require "rexml/parent"
-
1
require "rexml/parseexception"
-
1
require "rexml/namespace"
-
1
require 'rexml/entity'
-
1
require 'rexml/attlistdecl'
-
1
require 'rexml/xmltokens'
-
-
1
module REXML
-
# Represents an XML DOCTYPE declaration; that is, the contents of <!DOCTYPE
-
# ... >. DOCTYPES can be used to declare the DTD of a document, as well as
-
# being used to declare entities used in the document.
-
1
class DocType < Parent
-
1
include XMLTokens
-
1
START = "<!DOCTYPE"
-
1
STOP = ">"
-
1
SYSTEM = "SYSTEM"
-
1
PUBLIC = "PUBLIC"
-
1
DEFAULT_ENTITIES = {
-
'gt'=>EntityConst::GT,
-
'lt'=>EntityConst::LT,
-
'quot'=>EntityConst::QUOT,
-
"apos"=>EntityConst::APOS
-
}
-
-
# name is the name of the doctype
-
# external_id is the referenced DTD, if given
-
1
attr_reader :name, :external_id, :entities, :namespaces
-
-
# Constructor
-
#
-
# dt = DocType.new( 'foo', '-//I/Hate/External/IDs' )
-
# # <!DOCTYPE foo '-//I/Hate/External/IDs'>
-
# dt = DocType.new( doctype_to_clone )
-
# # Incomplete. Shallow clone of doctype
-
#
-
# +Note+ that the constructor:
-
#
-
# Doctype.new( Source.new( "<!DOCTYPE foo 'bar'>" ) )
-
#
-
# is _deprecated_. Do not use it. It will probably disappear.
-
1
def initialize( first, parent=nil )
-
1
@entities = DEFAULT_ENTITIES
-
1
@long_name = @uri = nil
-
1
if first.kind_of? String
-
super()
-
@name = first
-
@external_id = parent
-
1
elsif first.kind_of? DocType
-
super( parent )
-
@name = first.name
-
@external_id = first.external_id
-
1
elsif first.kind_of? Array
-
1
super( parent )
-
1
@name = first[0]
-
1
@external_id = first[1]
-
1
@long_name = first[2]
-
1
@uri = first[3]
-
elsif first.kind_of? Source
-
super( parent )
-
parser = Parsers::BaseParser.new( first )
-
event = parser.pull
-
if event[0] == :start_doctype
-
@name, @external_id, @long_name, @uri, = event[1..-1]
-
end
-
else
-
super()
-
end
-
end
-
-
1
def node_type
-
:doctype
-
end
-
-
1
def attributes_of element
-
rv = []
-
each do |child|
-
child.each do |key,val|
-
rv << Attribute.new(key,val)
-
end if child.kind_of? AttlistDecl and child.element_name == element
-
end
-
rv
-
end
-
-
1
def attribute_of element, attribute
-
att_decl = find do |child|
-
child.kind_of? AttlistDecl and
-
child.element_name == element and
-
child.include? attribute
-
end
-
return nil unless att_decl
-
att_decl[attribute]
-
end
-
-
1
def clone
-
DocType.new self
-
end
-
-
# output::
-
# Where to write the string
-
# indent::
-
# An integer. If -1, no indentation will be used; otherwise, the
-
# indentation will be this number of spaces, and children will be
-
# indented an additional amount.
-
# transitive::
-
# Ignored
-
# ie_hack::
-
# Ignored
-
1
def write( output, indent=0, transitive=false, ie_hack=false )
-
f = REXML::Formatters::Default.new
-
indent( output, indent )
-
output << START
-
output << ' '
-
output << @name
-
output << " #@external_id" if @external_id
-
output << " #{@long_name.inspect}" if @long_name
-
output << " #{@uri.inspect}" if @uri
-
unless @children.empty?
-
output << ' ['
-
@children.each { |child|
-
output << "\n"
-
f.write( child, output )
-
}
-
output << "\n]"
-
end
-
output << STOP
-
end
-
-
1
def context
-
@parent.context
-
end
-
-
1
def entity( name )
-
10001
@entities[name].unnormalized if @entities[name]
-
end
-
-
1
def add child
-
7
super(child)
-
7
@entities = DEFAULT_ENTITIES.clone if @entities == DEFAULT_ENTITIES
-
7
@entities[ child.name ] = child if child.kind_of? Entity
-
end
-
-
# This method retrieves the public identifier identifying the document's
-
# DTD.
-
#
-
# Method contributed by Henrik Martensson
-
1
def public
-
case @external_id
-
when "SYSTEM"
-
nil
-
when "PUBLIC"
-
strip_quotes(@long_name)
-
end
-
end
-
-
# This method retrieves the system identifier identifying the document's DTD
-
#
-
# Method contributed by Henrik Martensson
-
1
def system
-
case @external_id
-
when "SYSTEM"
-
strip_quotes(@long_name)
-
when "PUBLIC"
-
@uri.kind_of?(String) ? strip_quotes(@uri) : nil
-
end
-
end
-
-
# This method returns a list of notations that have been declared in the
-
# _internal_ DTD subset. Notations in the external DTD subset are not
-
# listed.
-
#
-
# Method contributed by Henrik Martensson
-
1
def notations
-
children().select {|node| node.kind_of?(REXML::NotationDecl)}
-
end
-
-
# Retrieves a named notation. Only notations declared in the internal
-
# DTD subset can be retrieved.
-
#
-
# Method contributed by Henrik Martensson
-
1
def notation(name)
-
notations.find { |notation_decl|
-
notation_decl.name == name
-
}
-
end
-
-
1
private
-
-
# Method contributed by Henrik Martensson
-
1
def strip_quotes(quoted_string)
-
quoted_string =~ /^[\'\"].*[\'\"]$/ ?
-
quoted_string[1, quoted_string.length-2] :
-
quoted_string
-
end
-
end
-
-
# We don't really handle any of these since we're not a validating
-
# parser, so we can be pretty dumb about them. All we need to be able
-
# to do is spew them back out on a write()
-
-
# This is an abstract class. You never use this directly; it serves as a
-
# parent class for the specific declarations.
-
1
class Declaration < Child
-
1
def initialize src
-
super()
-
@string = src
-
end
-
-
1
def to_s
-
@string+'>'
-
end
-
-
# == DEPRECATED
-
# See REXML::Formatters
-
#
-
1
def write( output, indent )
-
output << to_s
-
end
-
end
-
-
1
public
-
1
class ElementDecl < Declaration
-
1
def initialize( src )
-
super
-
end
-
end
-
-
1
class ExternalEntity < Child
-
1
def initialize( src )
-
super()
-
@entity = src
-
end
-
1
def to_s
-
@entity
-
end
-
1
def write( output, indent )
-
output << @entity
-
end
-
end
-
-
1
class NotationDecl < Child
-
1
attr_accessor :public, :system
-
1
def initialize name, middle, pub, sys
-
super(nil)
-
@name = name
-
@middle = middle
-
@public = pub
-
@system = sys
-
end
-
-
1
def to_s
-
notation = "<!NOTATION #{@name} #{@middle}"
-
notation << " #{@public.inspect}" if @public
-
notation << " #{@system.inspect}" if @system
-
notation << ">"
-
notation
-
end
-
-
1
def write( output, indent=-1 )
-
output << to_s
-
end
-
-
# This method retrieves the name of the notation.
-
#
-
# Method contributed by Henrik Martensson
-
1
def name
-
@name
-
end
-
end
-
end
-
1
require "rexml/element"
-
1
require "rexml/xmldecl"
-
1
require "rexml/source"
-
1
require "rexml/comment"
-
1
require "rexml/doctype"
-
1
require "rexml/instruction"
-
1
require "rexml/rexml"
-
1
require "rexml/parseexception"
-
1
require "rexml/output"
-
1
require "rexml/parsers/baseparser"
-
1
require "rexml/parsers/streamparser"
-
1
require "rexml/parsers/treeparser"
-
-
1
module REXML
-
# Represents a full XML document, including PIs, a doctype, etc. A
-
# Document has a single child that can be accessed by root().
-
# Note that if you want to have an XML declaration written for a document
-
# you create, you must add one; REXML documents do not write a default
-
# declaration for you. See |DECLARATION| and |write|.
-
1
class Document < Element
-
# A convenient default XML declaration. If you want an XML declaration,
-
# the easiest way to add one is mydoc << Document::DECLARATION
-
# +DEPRECATED+
-
# Use: mydoc << XMLDecl.default
-
1
DECLARATION = XMLDecl.default
-
-
# Constructor
-
# @param source if supplied, must be a Document, String, or IO.
-
# Documents have their context and Element attributes cloned.
-
# Strings are expected to be valid XML documents. IOs are expected
-
# to be sources of valid XML documents.
-
# @param context if supplied, contains the context of the document;
-
# this should be a Hash.
-
1
def initialize( source = nil, context = {} )
-
51
@entity_expansion_count = 0
-
51
super()
-
51
@context = context
-
51
return if source.nil?
-
51
if source.kind_of? Document
-
@context = source.context
-
super source
-
else
-
51
build( source )
-
end
-
end
-
-
1
def node_type
-
:document
-
end
-
-
# Should be obvious
-
1
def clone
-
Document.new self
-
end
-
-
# According to the XML spec, a root node has no expanded name
-
1
def expanded_name
-
''
-
#d = doc_type
-
#d ? d.name : "UNDEFINED"
-
end
-
-
1
alias :name :expanded_name
-
-
# We override this, because XMLDecls and DocTypes must go at the start
-
# of the document
-
1
def add( child )
-
150
if child.kind_of? XMLDecl
-
1
if @children[0].kind_of? XMLDecl
-
@children[0] = child
-
else
-
1
@children.unshift child
-
end
-
1
child.parent = self
-
149
elsif child.kind_of? DocType
-
# Find first Element or DocType node and insert the decl right
-
# before it. If there is no such node, just insert the child at the
-
# end. If there is a child and it is an DocType, then replace it.
-
1
insert_before_index = @children.find_index { |x|
-
2
x.kind_of?(Element) || x.kind_of?(DocType)
-
}
-
1
if insert_before_index # Not null = not end of list
-
if @children[ insert_before_index ].kind_of? DocType
-
@children[ insert_before_index ] = child
-
else
-
@children[ insert_before_index-1, 0 ] = child
-
end
-
else # Insert at end of list
-
1
@children << child
-
end
-
1
child.parent = self
-
else
-
148
rv = super
-
148
raise "attempted adding second root element to document" if @elements.size > 1
-
148
rv
-
end
-
end
-
1
alias :<< :add
-
-
1
def add_element(arg=nil, arg2=nil)
-
51
rv = super
-
51
raise "attempted adding second root element to document" if @elements.size > 1
-
51
rv
-
end
-
-
# @return the root Element of the document, or nil if this document
-
# has no children.
-
1
def root
-
20201
elements[1]
-
#self
-
#@children.find { |item| item.kind_of? Element }
-
end
-
-
# @return the DocType child of the document, if one exists,
-
# and nil otherwise.
-
1
def doctype
-
2132
@children.find { |item| item.kind_of? DocType }
-
end
-
-
# @return the XMLDecl of this document; if no XMLDecl has been
-
# set, the default declaration is returned.
-
1
def xml_decl
-
rv = @children[0]
-
return rv if rv.kind_of? XMLDecl
-
rv = @children.unshift(XMLDecl.default)[0]
-
end
-
-
# @return the XMLDecl version of this document as a String.
-
# If no XMLDecl has been set, returns the default version.
-
1
def version
-
xml_decl().version
-
end
-
-
# @return the XMLDecl encoding of this document as an
-
# Encoding object.
-
# If no XMLDecl has been set, returns the default encoding.
-
1
def encoding
-
xml_decl().encoding
-
end
-
-
# @return the XMLDecl standalone value of this document as a String.
-
# If no XMLDecl has been set, returns the default setting.
-
1
def stand_alone?
-
xml_decl().stand_alone?
-
end
-
-
# Write the XML tree out, optionally with indent. This writes out the
-
# entire XML document, including XML declarations, doctype declarations,
-
# and processing instructions (if any are given).
-
#
-
# A controversial point is whether Document should always write the XML
-
# declaration (<?xml version='1.0'?>) whether or not one is given by the
-
# user (or source document). REXML does not write one if one was not
-
# specified, because it adds unnecessary bandwidth to applications such
-
# as XML-RPC.
-
#
-
# See also the classes in the rexml/formatters package for the proper way
-
# to change the default formatting of XML output
-
#
-
# _Examples_
-
# Document.new("<a><b/></a>").serialize
-
#
-
# output_string = ""
-
# tr = Transitive.new( output_string )
-
# Document.new("<a><b/></a>").serialize( tr )
-
#
-
# output::
-
# output an object which supports '<< string'; this is where the
-
# document will be written.
-
# indent::
-
# An integer. If -1, no indenting will be used; otherwise, the
-
# indentation will be twice this number of spaces, and children will be
-
# indented an additional amount. For a value of 3, every item will be
-
# indented 3 more levels, or 6 more spaces (2 * 3). Defaults to -1
-
# transitive::
-
# If transitive is true and indent is >= 0, then the output will be
-
# pretty-printed in such a way that the added whitespace does not affect
-
# the absolute *value* of the document -- that is, it leaves the value
-
# and number of Text nodes in the document unchanged.
-
# ie_hack::
-
# Internet Explorer is the worst piece of crap to have ever been
-
# written, with the possible exception of Windows itself. Since IE is
-
# unable to parse proper XML, we have to provide a hack to generate XML
-
# that IE's limited abilities can handle. This hack inserts a space
-
# before the /> on empty tags. Defaults to false
-
1
def write( output=$stdout, indent=-1, transitive=false, ie_hack=false )
-
if xml_decl.encoding != 'UTF-8' && !output.kind_of?(Output)
-
output = Output.new( output, xml_decl.encoding )
-
end
-
formatter = if indent > -1
-
if transitive
-
require "rexml/formatters/transitive"
-
REXML::Formatters::Transitive.new( indent, ie_hack )
-
else
-
REXML::Formatters::Pretty.new( indent, ie_hack )
-
end
-
else
-
REXML::Formatters::Default.new( ie_hack )
-
end
-
formatter.write( self, output )
-
end
-
-
-
1
def Document::parse_stream( source, listener )
-
Parsers::StreamParser.new( source, listener ).parse
-
end
-
-
1
@@entity_expansion_limit = 10_000
-
-
# Set the entity expansion limit. By default the limit is set to 10000.
-
1
def Document::entity_expansion_limit=( val )
-
@@entity_expansion_limit = val
-
end
-
-
# Get the entity expansion limit. By default the limit is set to 10000.
-
1
def Document::entity_expansion_limit
-
return @@entity_expansion_limit
-
end
-
-
1
attr_reader :entity_expansion_count
-
-
1
def record_entity_expansion
-
10001
@entity_expansion_count += 1
-
10001
if @entity_expansion_count > @@entity_expansion_limit
-
1
raise "number of entity expansions exceeded, processing aborted."
-
end
-
end
-
-
1
private
-
1
def build( source )
-
51
Parsers::TreeParser.new( source, self ).parse
-
end
-
end
-
end
-
1
require "rexml/parent"
-
1
require "rexml/namespace"
-
1
require "rexml/attribute"
-
1
require "rexml/cdata"
-
1
require "rexml/xpath"
-
1
require "rexml/parseexception"
-
-
1
module REXML
-
# An implementation note about namespaces:
-
# As we parse, when we find namespaces we put them in a hash and assign
-
# them a unique ID. We then convert the namespace prefix for the node
-
# to the unique ID. This makes namespace lookup much faster for the
-
# cost of extra memory use. We save the namespace prefix for the
-
# context node and convert it back when we write it.
-
1
@@namespaces = {}
-
-
# Represents a tagged XML element. Elements are characterized by
-
# having children, attributes, and names, and can themselves be
-
# children.
-
1
class Element < Parent
-
1
include Namespace
-
-
1
UNDEFINED = "UNDEFINED"; # The default name
-
-
# Mechanisms for accessing attributes and child elements of this
-
# element.
-
1
attr_reader :attributes, :elements
-
# The context holds information about the processing environment, such as
-
# whitespace handling.
-
1
attr_accessor :context
-
-
# Constructor
-
# arg::
-
# if not supplied, will be set to the default value.
-
# If a String, the name of this object will be set to the argument.
-
# If an Element, the object will be shallowly cloned; name,
-
# attributes, and namespaces will be copied. Children will +not+ be
-
# copied.
-
# parent::
-
# if supplied, must be a Parent, and will be used as
-
# the parent of this object.
-
# context::
-
# If supplied, must be a hash containing context items. Context items
-
# include:
-
# * <tt>:respect_whitespace</tt> the value of this is :+all+ or an array of
-
# strings being the names of the elements to respect
-
# whitespace for. Defaults to :+all+.
-
# * <tt>:compress_whitespace</tt> the value can be :+all+ or an array of
-
# strings being the names of the elements to ignore whitespace on.
-
# Overrides :+respect_whitespace+.
-
# * <tt>:ignore_whitespace_nodes</tt> the value can be :+all+ or an array
-
# of strings being the names of the elements in which to ignore
-
# whitespace-only nodes. If this is set, Text nodes which contain only
-
# whitespace will not be added to the document tree.
-
# * <tt>:raw</tt> can be :+all+, or an array of strings being the names of
-
# the elements to process in raw mode. In raw mode, special
-
# characters in text is not converted to or from entities.
-
1
def initialize( arg = UNDEFINED, parent=nil, context=nil )
-
231
super(parent)
-
-
231
@elements = Elements.new(self)
-
231
@attributes = Attributes.new(self)
-
231
@context = context
-
-
231
if arg.kind_of? String
-
231
self.name = arg
-
elsif arg.kind_of? Element
-
self.name = arg.expanded_name
-
arg.attributes.each_attribute{ |attribute|
-
@attributes << Attribute.new( attribute )
-
}
-
@context = arg.context
-
end
-
end
-
-
1
def inspect
-
rv = "<#@expanded_name"
-
-
@attributes.each_attribute do |attr|
-
rv << " "
-
attr.write( rv, 0 )
-
end
-
-
if children.size > 0
-
rv << "> ... </>"
-
else
-
rv << "/>"
-
end
-
end
-
-
-
# Creates a shallow copy of self.
-
# d = Document.new "<a><b/><b/><c><d/></c></a>"
-
# new_a = d.root.clone
-
# puts new_a # => "<a/>"
-
1
def clone
-
self.class.new self
-
end
-
-
# Evaluates to the root node of the document that this element
-
# belongs to. If this element doesn't belong to a document, but does
-
# belong to another Element, the parent's root will be returned, until the
-
# earliest ancestor is found.
-
#
-
# Note that this is not the same as the document element.
-
# In the following example, <a> is the document element, and the root
-
# node is the parent node of the document element. You may ask yourself
-
# why the root node is useful: consider the doctype and XML declaration,
-
# and any processing instructions before the document element... they
-
# are children of the root node, or siblings of the document element.
-
# The only time this isn't true is when an Element is created that is
-
# not part of any Document. In this case, the ancestor that has no
-
# parent acts as the root node.
-
# d = Document.new '<a><b><c/></b></a>'
-
# a = d[1] ; c = a[1][1]
-
# d.root_node == d # TRUE
-
# a.root_node # namely, d
-
# c.root_node # again, d
-
1
def root_node
-
parent.nil? ? self : parent.root_node
-
end
-
-
1
def root
-
1220
return elements[1] if self.kind_of? Document
-
1220
return self if parent.kind_of? Document or parent.nil?
-
625
return parent.root
-
end
-
-
# Evaluates to the document to which this element belongs, or nil if this
-
# element doesn't belong to a document.
-
1
def document
-
20694
rt = root
-
20694
rt.parent if rt
-
end
-
-
# Evaluates to +true+ if whitespace is respected for this element. This
-
# is the case if:
-
# 1. Neither :+respect_whitespace+ nor :+compress_whitespace+ has any value
-
# 2. The context has :+respect_whitespace+ set to :+all+ or
-
# an array containing the name of this element, and
-
# :+compress_whitespace+ isn't set to :+all+ or an array containing the
-
# name of this element.
-
# The evaluation is tested against +expanded_name+, and so is namespace
-
# sensitive.
-
1
def whitespace
-
376
@whitespace = nil
-
376
if @context
-
376
if @context[:respect_whitespace]
-
@whitespace = (@context[:respect_whitespace] == :all or
-
@context[:respect_whitespace].include? expanded_name)
-
end
-
@whitespace = false if (@context[:compress_whitespace] and
-
(@context[:compress_whitespace] == :all or
-
376
@context[:compress_whitespace].include? expanded_name)
-
)
-
end
-
376
@whitespace = true unless @whitespace == false
-
376
@whitespace
-
end
-
-
1
def ignore_whitespace_nodes
-
376
@ignore_whitespace_nodes = false
-
376
if @context
-
376
if @context[:ignore_whitespace_nodes]
-
@ignore_whitespace_nodes =
-
(@context[:ignore_whitespace_nodes] == :all or
-
@context[:ignore_whitespace_nodes].include? expanded_name)
-
end
-
end
-
end
-
-
# Evaluates to +true+ if raw mode is set for this element. This
-
# is the case if the context has :+raw+ set to :+all+ or
-
# an array containing the name of this element.
-
#
-
# The evaluation is tested against +expanded_name+, and so is namespace
-
# sensitive.
-
1
def raw
-
@raw = (@context and @context[:raw] and
-
(@context[:raw] == :all or
-
@context[:raw].include? expanded_name))
-
@raw
-
end
-
-
#once :whitespace, :raw, :ignore_whitespace_nodes
-
-
#################################################
-
# Namespaces #
-
#################################################
-
-
# Evaluates to an +Array+ containing the prefixes (names) of all defined
-
# namespaces at this context node.
-
# doc = Document.new("<a xmlns:x='1' xmlns:y='2'><b/><c xmlns:z='3'/></a>")
-
# doc.elements['//b'].prefixes # -> ['x', 'y']
-
1
def prefixes
-
prefixes = []
-
prefixes = parent.prefixes if parent
-
prefixes |= attributes.prefixes
-
return prefixes
-
end
-
-
1
def namespaces
-
namespaces = {}
-
namespaces = parent.namespaces if parent
-
namespaces = namespaces.merge( attributes.namespaces )
-
return namespaces
-
end
-
-
# Evalutas to the URI for a prefix, or the empty string if no such
-
# namespace is declared for this element. Evaluates recursively for
-
# ancestors. Returns the default namespace, if there is one.
-
# prefix::
-
# the prefix to search for. If not supplied, returns the default
-
# namespace if one exists
-
# Returns::
-
# the namespace URI as a String, or nil if no such namespace
-
# exists. If the namespace is undefined, returns an empty string
-
# doc = Document.new("<a xmlns='1' xmlns:y='2'><b/><c xmlns:z='3'/></a>")
-
# b = doc.elements['//b']
-
# b.namespace # -> '1'
-
# b.namespace("y") # -> '2'
-
1
def namespace(prefix=nil)
-
if prefix.nil?
-
prefix = prefix()
-
end
-
if prefix == ''
-
prefix = "xmlns"
-
else
-
prefix = "xmlns:#{prefix}" unless prefix[0,5] == 'xmlns'
-
end
-
ns = attributes[ prefix ]
-
ns = parent.namespace(prefix) if ns.nil? and parent
-
ns = '' if ns.nil? and prefix == 'xmlns'
-
return ns
-
end
-
-
# Adds a namespace to this element.
-
# prefix::
-
# the prefix string, or the namespace URI if +uri+ is not
-
# supplied
-
# uri::
-
# the namespace URI. May be nil, in which +prefix+ is used as
-
# the URI
-
# Evaluates to: this Element
-
# a = Element.new("a")
-
# a.add_namespace("xmlns:foo", "bar" )
-
# a.add_namespace("foo", "bar") # shorthand for previous line
-
# a.add_namespace("twiddle")
-
# puts a #-> <a xmlns:foo='bar' xmlns='twiddle'/>
-
1
def add_namespace( prefix, uri=nil )
-
unless uri
-
@attributes["xmlns"] = prefix
-
else
-
prefix = "xmlns:#{prefix}" unless prefix =~ /^xmlns:/
-
@attributes[ prefix ] = uri
-
end
-
self
-
end
-
-
# Removes a namespace from this node. This only works if the namespace is
-
# actually declared in this node. If no argument is passed, deletes the
-
# default namespace.
-
#
-
# Evaluates to: this element
-
# doc = Document.new "<a xmlns:foo='bar' xmlns='twiddle'/>"
-
# doc.root.delete_namespace
-
# puts doc # -> <a xmlns:foo='bar'/>
-
# doc.root.delete_namespace 'foo'
-
# puts doc # -> <a/>
-
1
def delete_namespace namespace="xmlns"
-
namespace = "xmlns:#{namespace}" unless namespace == 'xmlns'
-
attribute = attributes.get_attribute(namespace)
-
attribute.remove unless attribute.nil?
-
self
-
end
-
-
#################################################
-
# Elements #
-
#################################################
-
-
# Adds a child to this element, optionally setting attributes in
-
# the element.
-
# element::
-
# optional. If Element, the element is added.
-
# Otherwise, a new Element is constructed with the argument (see
-
# Element.initialize).
-
# attrs::
-
# If supplied, must be a Hash containing String name,value
-
# pairs, which will be used to set the attributes of the new Element.
-
# Returns:: the Element that was added
-
# el = doc.add_element 'my-tag'
-
# el = doc.add_element 'my-tag', {'attr1'=>'val1', 'attr2'=>'val2'}
-
# el = Element.new 'my-tag'
-
# doc.add_element el
-
1
def add_element element, attrs=nil
-
180
raise "First argument must be either an element name, or an Element object" if element.nil?
-
180
el = @elements.add(element)
-
attrs.each do |key, value|
-
el.attributes[key]=value
-
180
end if attrs.kind_of? Hash
-
180
el
-
end
-
-
# Deletes a child element.
-
# element::
-
# Must be an +Element+, +String+, or +Integer+. If Element,
-
# the element is removed. If String, the element is found (via XPath)
-
# and removed. <em>This means that any parent can remove any
-
# descendant.<em> If Integer, the Element indexed by that number will be
-
# removed.
-
# Returns:: the element that was removed.
-
# doc.delete_element "/a/b/c[@id='4']"
-
# doc.delete_element doc.elements["//k"]
-
# doc.delete_element 1
-
1
def delete_element element
-
@elements.delete element
-
end
-
-
# Evaluates to +true+ if this element has at least one child Element
-
# doc = Document.new "<a><b/><c>Text</c></a>"
-
# doc.root.has_elements # -> true
-
# doc.elements["/a/b"].has_elements # -> false
-
# doc.elements["/a/c"].has_elements # -> false
-
1
def has_elements?
-
180
!@elements.empty?
-
end
-
-
# Iterates through the child elements, yielding for each Element that
-
# has a particular attribute set.
-
# key::
-
# the name of the attribute to search for
-
# value::
-
# the value of the attribute
-
# max::
-
# (optional) causes this method to return after yielding
-
# for this number of matching children
-
# name::
-
# (optional) if supplied, this is an XPath that filters
-
# the children to check.
-
#
-
# doc = Document.new "<a><b @id='1'/><c @id='2'/><d @id='1'/><e/></a>"
-
# # Yields b, c, d
-
# doc.root.each_element_with_attribute( 'id' ) {|e| p e}
-
# # Yields b, d
-
# doc.root.each_element_with_attribute( 'id', '1' ) {|e| p e}
-
# # Yields b
-
# doc.root.each_element_with_attribute( 'id', '1', 1 ) {|e| p e}
-
# # Yields d
-
# doc.root.each_element_with_attribute( 'id', '1', 0, 'd' ) {|e| p e}
-
1
def each_element_with_attribute( key, value=nil, max=0, name=nil, &block ) # :yields: Element
-
each_with_something( proc {|child|
-
if value.nil?
-
child.attributes[key] != nil
-
else
-
child.attributes[key]==value
-
end
-
}, max, name, &block )
-
end
-
-
# Iterates through the children, yielding for each Element that
-
# has a particular text set.
-
# text::
-
# the text to search for. If nil, or not supplied, will iterate
-
# over all +Element+ children that contain at least one +Text+ node.
-
# max::
-
# (optional) causes this method to return after yielding
-
# for this number of matching children
-
# name::
-
# (optional) if supplied, this is an XPath that filters
-
# the children to check.
-
#
-
# doc = Document.new '<a><b>b</b><c>b</c><d>d</d><e/></a>'
-
# # Yields b, c, d
-
# doc.each_element_with_text {|e|p e}
-
# # Yields b, c
-
# doc.each_element_with_text('b'){|e|p e}
-
# # Yields b
-
# doc.each_element_with_text('b', 1){|e|p e}
-
# # Yields d
-
# doc.each_element_with_text(nil, 0, 'd'){|e|p e}
-
1
def each_element_with_text( text=nil, max=0, name=nil, &block ) # :yields: Element
-
each_with_something( proc {|child|
-
if text.nil?
-
child.has_text?
-
else
-
child.text == text
-
end
-
}, max, name, &block )
-
end
-
-
# Synonym for Element.elements.each
-
1
def each_element( xpath=nil, &block ) # :yields: Element
-
54
@elements.each( xpath, &block )
-
end
-
-
# Synonym for Element.to_a
-
# This is a little slower than calling elements.each directly.
-
# xpath:: any XPath by which to search for elements in the tree
-
# Returns:: an array of Elements that match the supplied path
-
1
def get_elements( xpath )
-
@elements.to_a( xpath )
-
end
-
-
# Returns the next sibling that is an element, or nil if there is
-
# no Element sibling after this one
-
# doc = Document.new '<a><b/>text<c/></a>'
-
# doc.root.elements['b'].next_element #-> <c/>
-
# doc.root.elements['c'].next_element #-> nil
-
1
def next_element
-
element = next_sibling
-
element = element.next_sibling until element.nil? or element.kind_of? Element
-
return element
-
end
-
-
# Returns the previous sibling that is an element, or nil if there is
-
# no Element sibling prior to this one
-
# doc = Document.new '<a><b/>text<c/></a>'
-
# doc.root.elements['c'].previous_element #-> <b/>
-
# doc.root.elements['b'].previous_element #-> nil
-
1
def previous_element
-
element = previous_sibling
-
element = element.previous_sibling until element.nil? or element.kind_of? Element
-
return element
-
end
-
-
-
#################################################
-
# Text #
-
#################################################
-
-
# Evaluates to +true+ if this element has at least one Text child
-
1
def has_text?
-
129
not text().nil?
-
end
-
-
# A convenience method which returns the String value of the _first_
-
# child text element, if one exists, and +nil+ otherwise.
-
#
-
# <em>Note that an element may have multiple Text elements, perhaps
-
# separated by other children</em>. Be aware that this method only returns
-
# the first Text node.
-
#
-
# This method returns the +value+ of the first text child node, which
-
# ignores the +raw+ setting, so always returns normalized text. See
-
# the Text::value documentation.
-
#
-
# doc = Document.new "<p>some text <b>this is bold!</b> more text</p>"
-
# # The element 'p' has two text elements, "some text " and " more text".
-
# doc.root.text #-> "some text "
-
1
def text( path = nil )
-
129
rv = get_text(path)
-
129
return rv.value unless rv.nil?
-
nil
-
end
-
-
# Returns the first child Text node, if any, or +nil+ otherwise.
-
# This method returns the actual +Text+ node, rather than the String content.
-
# doc = Document.new "<p>some text <b>this is bold!</b> more text</p>"
-
# # The element 'p' has two text elements, "some text " and " more text".
-
# doc.root.get_text.value #-> "some text "
-
1
def get_text path = nil
-
129
rv = nil
-
129
if path
-
element = @elements[ path ]
-
rv = element.get_text unless element.nil?
-
else
-
231
rv = @children.find { |node| node.kind_of? Text }
-
end
-
129
return rv
-
end
-
-
# Sets the first Text child of this object. See text() for a
-
# discussion about Text children.
-
#
-
# If a Text child already exists, the child is replaced by this
-
# content. This means that Text content can be deleted by calling
-
# this method with a nil argument. In this case, the next Text
-
# child becomes the first Text child. In no case is the order of
-
# any siblings disturbed.
-
# text::
-
# If a String, a new Text child is created and added to
-
# this Element as the first Text child. If Text, the text is set
-
# as the first Child element. If nil, then any existing first Text
-
# child is removed.
-
# Returns:: this Element.
-
# doc = Document.new '<a><b/></a>'
-
# doc.root.text = 'Sean' #-> '<a><b/>Sean</a>'
-
# doc.root.text = 'Elliott' #-> '<a><b/>Elliott</a>'
-
# doc.root.add_element 'c' #-> '<a><b/>Elliott<c/></a>'
-
# doc.root.text = 'Russell' #-> '<a><b/>Russell<c/></a>'
-
# doc.root.text = nil #-> '<a><b/><c/></a>'
-
1
def text=( text )
-
if text.kind_of? String
-
text = Text.new( text, whitespace(), nil, raw() )
-
elsif !text.nil? and !text.kind_of? Text
-
text = Text.new( text.to_s, whitespace(), nil, raw() )
-
end
-
old_text = get_text
-
if text.nil?
-
old_text.remove unless old_text.nil?
-
else
-
if old_text.nil?
-
self << text
-
else
-
old_text.replace_with( text )
-
end
-
end
-
return self
-
end
-
-
# A helper method to add a Text child. Actual Text instances can
-
# be added with regular Parent methods, such as add() and <<()
-
# text::
-
# if a String, a new Text instance is created and added
-
# to the parent. If Text, the object is added directly.
-
# Returns:: this Element
-
# e = Element.new('a') #-> <e/>
-
# e.add_text 'foo' #-> <e>foo</e>
-
# e.add_text Text.new(' bar') #-> <e>foo bar</e>
-
# Note that at the end of this example, the branch has <b>3</b> nodes; the 'e'
-
# element and <b>2</b> Text node children.
-
1
def add_text( text )
-
if text.kind_of? String
-
if @children[-1].kind_of? Text
-
@children[-1] << text
-
return
-
end
-
text = Text.new( text, whitespace(), nil, raw() )
-
end
-
self << text unless text.nil?
-
return self
-
end
-
-
1
def node_type
-
183
:element
-
end
-
-
1
def xpath
-
path_elements = []
-
cur = self
-
path_elements << __to_xpath_helper( self )
-
while cur.parent
-
cur = cur.parent
-
path_elements << __to_xpath_helper( cur )
-
end
-
return path_elements.reverse.join( "/" )
-
end
-
-
#################################################
-
# Attributes #
-
#################################################
-
-
1
def attribute( name, namespace=nil )
-
prefix = nil
-
if namespaces.respond_to? :key
-
prefix = namespaces.key(namespace) if namespace
-
else
-
prefix = namespaces.index(namespace) if namespace
-
end
-
prefix = nil if prefix == 'xmlns'
-
-
ret_val =
-
attributes.get_attribute( "#{prefix ? prefix + ':' : ''}#{name}" )
-
-
return ret_val unless ret_val.nil?
-
return nil if prefix.nil?
-
-
# now check that prefix'es namespace is not the same as the
-
# default namespace
-
return nil unless ( namespaces[ prefix ] == namespaces[ 'xmlns' ] )
-
-
attributes.get_attribute( name )
-
-
end
-
-
# Evaluates to +true+ if this element has any attributes set, false
-
# otherwise.
-
1
def has_attributes?
-
return !@attributes.empty?
-
end
-
-
# Adds an attribute to this element, overwriting any existing attribute
-
# by the same name.
-
# key::
-
# can be either an Attribute or a String. If an Attribute,
-
# the attribute is added to the list of Element attributes. If String,
-
# the argument is used as the name of the new attribute, and the value
-
# parameter must be supplied.
-
# value::
-
# Required if +key+ is a String, and ignored if the first argument is
-
# an Attribute. This is a String, and is used as the value
-
# of the new Attribute. This should be the unnormalized value of the
-
# attribute (without entities).
-
# Returns:: the Attribute added
-
# e = Element.new 'e'
-
# e.add_attribute( 'a', 'b' ) #-> <e a='b'/>
-
# e.add_attribute( 'x:a', 'c' ) #-> <e a='b' x:a='c'/>
-
# e.add_attribute Attribute.new('b', 'd') #-> <e a='b' x:a='c' b='d'/>
-
1
def add_attribute( key, value=nil )
-
if key.kind_of? Attribute
-
@attributes << key
-
else
-
@attributes[key] = value
-
end
-
end
-
-
# Add multiple attributes to this element.
-
# hash:: is either a hash, or array of arrays
-
# el.add_attributes( {"name1"=>"value1", "name2"=>"value2"} )
-
# el.add_attributes( [ ["name1","value1"], ["name2"=>"value2"] ] )
-
1
def add_attributes hash
-
if hash.kind_of? Hash
-
hash.each_pair {|key, value| @attributes[key] = value }
-
elsif hash.kind_of? Array
-
hash.each { |value| @attributes[ value[0] ] = value[1] }
-
end
-
end
-
-
# Removes an attribute
-
# key::
-
# either an Attribute or a String. In either case, the
-
# attribute is found by matching the attribute name to the argument,
-
# and then removed. If no attribute is found, no action is taken.
-
# Returns::
-
# the attribute removed, or nil if this Element did not contain
-
# a matching attribute
-
# e = Element.new('E')
-
# e.add_attribute( 'name', 'Sean' ) #-> <E name='Sean'/>
-
# r = e.add_attribute( 'sur:name', 'Russell' ) #-> <E name='Sean' sur:name='Russell'/>
-
# e.delete_attribute( 'name' ) #-> <E sur:name='Russell'/>
-
# e.delete_attribute( r ) #-> <E/>
-
1
def delete_attribute(key)
-
attr = @attributes.get_attribute(key)
-
attr.remove unless attr.nil?
-
end
-
-
#################################################
-
# Other Utilities #
-
#################################################
-
-
# Get an array of all CData children.
-
# IMMUTABLE
-
1
def cdatas
-
find_all { |child| child.kind_of? CData }.freeze
-
end
-
-
# Get an array of all Comment children.
-
# IMMUTABLE
-
1
def comments
-
find_all { |child| child.kind_of? Comment }.freeze
-
end
-
-
# Get an array of all Instruction children.
-
# IMMUTABLE
-
1
def instructions
-
find_all { |child| child.kind_of? Instruction }.freeze
-
end
-
-
# Get an array of all Text children.
-
# IMMUTABLE
-
1
def texts
-
580
find_all { |child| child.kind_of? Text }.freeze
-
end
-
-
# == DEPRECATED
-
# See REXML::Formatters
-
#
-
# Writes out this element, and recursively, all children.
-
# output::
-
# output an object which supports '<< string'; this is where the
-
# document will be written.
-
# indent::
-
# An integer. If -1, no indenting will be used; otherwise, the
-
# indentation will be this number of spaces, and children will be
-
# indented an additional amount. Defaults to -1
-
# transitive::
-
# If transitive is true and indent is >= 0, then the output will be
-
# pretty-printed in such a way that the added whitespace does not affect
-
# the parse tree of the document
-
# ie_hack::
-
# Internet Explorer is the worst piece of crap to have ever been
-
# written, with the possible exception of Windows itself. Since IE is
-
# unable to parse proper XML, we have to provide a hack to generate XML
-
# that IE's limited abilities can handle. This hack inserts a space
-
# before the /> on empty tags. Defaults to false
-
#
-
# out = ''
-
# doc.write( out ) #-> doc is written to the string 'out'
-
# doc.write( $stdout ) #-> doc written to the console
-
1
def write(output=$stdout, indent=-1, transitive=false, ie_hack=false)
-
Kernel.warn("#{self.class.name}.write is deprecated. See REXML::Formatters")
-
formatter = if indent > -1
-
if transitive
-
require "rexml/formatters/transitive"
-
REXML::Formatters::Transitive.new( indent, ie_hack )
-
else
-
REXML::Formatters::Pretty.new( indent, ie_hack )
-
end
-
else
-
REXML::Formatters::Default.new( ie_hack )
-
end
-
formatter.write( self, output )
-
end
-
-
-
1
private
-
1
def __to_xpath_helper node
-
rv = node.expanded_name.clone
-
if node.parent
-
results = node.parent.find_all {|n|
-
n.kind_of?(REXML::Element) and n.expanded_name == node.expanded_name
-
}
-
if results.length > 1
-
idx = results.index( node )
-
rv << "[#{idx+1}]"
-
end
-
end
-
rv
-
end
-
-
# A private helper method
-
1
def each_with_something( test, max=0, name=nil )
-
num = 0
-
@elements.each( name ){ |child|
-
yield child if test.call(child) and num += 1
-
return if max>0 and num == max
-
}
-
end
-
end
-
-
########################################################################
-
# ELEMENTS #
-
########################################################################
-
-
# A class which provides filtering of children for Elements, and
-
# XPath search support. You are expected to only encounter this class as
-
# the <tt>element.elements</tt> object. Therefore, you are
-
# _not_ expected to instantiate this yourself.
-
1
class Elements
-
1
include Enumerable
-
# Constructor
-
# parent:: the parent Element
-
1
def initialize parent
-
231
@element = parent
-
end
-
-
# Fetches a child element. Filters only Element children, regardless of
-
# the XPath match.
-
# index::
-
# the search parameter. This is either an Integer, which
-
# will be used to find the index'th child Element, or an XPath,
-
# which will be used to search for the Element. <em>Because
-
# of the nature of XPath searches, any element in the connected XML
-
# document can be fetched through any other element.</em> <b>The
-
# Integer index is 1-based, not 0-based.</b> This means that the first
-
# child element is at index 1, not 0, and the +n+th element is at index
-
# +n+, not <tt>n-1</tt>. This is because XPath indexes element children
-
# starting from 1, not 0, and the indexes should be the same.
-
# name::
-
# optional, and only used in the first argument is an
-
# Integer. In that case, the index'th child Element that has the
-
# supplied name will be returned. Note again that the indexes start at 1.
-
# Returns:: the first matching Element, or nil if no child matched
-
# doc = Document.new '<a><b/><c id="1"/><c id="2"/><d/></a>'
-
# doc.root.elements[1] #-> <b/>
-
# doc.root.elements['c'] #-> <c id="1"/>
-
# doc.root.elements[2,'c'] #-> <c id="2"/>
-
1
def []( index, name=nil)
-
20201
if index.kind_of? Integer
-
20201
raise "index (#{index}) must be >= 1" if index < 1
-
20201
name = literalize(name) if name
-
20201
num = 0
-
20201
@element.find { |child|
-
child.kind_of? Element and
-
100316
(name.nil? ? true : child.has_name?( name )) and
-
20152
(num += 1) == index
-
}
-
else
-
return XPath::first( @element, index )
-
#{ |element|
-
# return element if element.kind_of? Element
-
#}
-
#return nil
-
end
-
end
-
-
# Sets an element, replacing any previous matching element. If no
-
# existing element is found ,the element is added.
-
# index:: Used to find a matching element to replace. See []().
-
# element::
-
# The element to replace the existing element with
-
# the previous element
-
# Returns:: nil if no previous element was found.
-
#
-
# doc = Document.new '<a/>'
-
# doc.root.elements[10] = Element.new('b') #-> <a><b/></a>
-
# doc.root.elements[1] #-> <b/>
-
# doc.root.elements[1] = Element.new('c') #-> <a><c/></a>
-
# doc.root.elements['c'] = Element.new('d') #-> <a><d/></a>
-
1
def []=( index, element )
-
previous = self[index]
-
if previous.nil?
-
@element.add element
-
else
-
previous.replace_with element
-
end
-
return previous
-
end
-
-
# Returns +true+ if there are no +Element+ children, +false+ otherwise
-
1
def empty?
-
398
@element.find{ |child| child.kind_of? Element}.nil?
-
end
-
-
# Returns the index of the supplied child (starting at 1), or -1 if
-
# the element is not a child
-
# element:: an +Element+ child
-
1
def index element
-
rv = 0
-
found = @element.find do |child|
-
child.kind_of? Element and
-
(rv += 1) and
-
child == element
-
end
-
return rv if found == element
-
return -1
-
end
-
-
# Deletes a child Element
-
# element::
-
# Either an Element, which is removed directly; an
-
# xpath, where the first matching child is removed; or an Integer,
-
# where the n'th Element is removed.
-
# Returns:: the removed child
-
# doc = Document.new '<a><b/><c/><c id="1"/></a>'
-
# b = doc.root.elements[1]
-
# doc.root.elements.delete b #-> <a><c/><c id="1"/></a>
-
# doc.elements.delete("a/c[@id='1']") #-> <a><c/></a>
-
# doc.root.elements.delete 1 #-> <a/>
-
1
def delete element
-
if element.kind_of? Element
-
@element.delete element
-
else
-
el = self[element]
-
el.remove if el
-
end
-
end
-
-
# Removes multiple elements. Filters for Element children, regardless of
-
# XPath matching.
-
# xpath:: all elements matching this String path are removed.
-
# Returns:: an Array of Elements that have been removed
-
# doc = Document.new '<a><c/><c/><c/><c/></a>'
-
# deleted = doc.elements.delete_all 'a/c' #-> [<c/>, <c/>, <c/>, <c/>]
-
1
def delete_all( xpath )
-
rv = []
-
XPath::each( @element, xpath) {|element|
-
rv << element if element.kind_of? Element
-
}
-
rv.each do |element|
-
@element.delete element
-
element.remove
-
end
-
return rv
-
end
-
-
# Adds an element
-
# element::
-
# if supplied, is either an Element, String, or
-
# Source (see Element.initialize). If not supplied or nil, a
-
# new, default Element will be constructed
-
# Returns:: the added Element
-
# a = Element.new('a')
-
# a.elements.add(Element.new('b')) #-> <a><b/></a>
-
# a.elements.add('c') #-> <a><b/><c/></a>
-
1
def add element=nil
-
360
if element.nil?
-
Element.new("", self, @element.context)
-
360
elsif not element.kind_of?(Element)
-
180
Element.new(element, self, @element.context)
-
else
-
180
@element << element
-
180
element.context = @element.context
-
180
element
-
end
-
end
-
-
1
alias :<< :add
-
-
# Iterates through all of the child Elements, optionally filtering
-
# them by a given XPath
-
# xpath::
-
# optional. If supplied, this is a String XPath, and is used to
-
# filter the children, so that only matching children are yielded. Note
-
# that XPaths are automatically filtered for Elements, so that
-
# non-Element children will not be yielded
-
# doc = Document.new '<a><b/><c/><d/>sean<b/><c/><d/></a>'
-
# doc.root.each {|e|p e} #-> Yields b, c, d, b, c, d elements
-
# doc.root.each('b') {|e|p e} #-> Yields b, b elements
-
# doc.root.each('child::node()') {|e|p e}
-
# #-> Yields <b/>, <c/>, <d/>, <b/>, <c/>, <d/>
-
# XPath.each(doc.root, 'child::node()', &block)
-
# #-> Yields <b/>, <c/>, <d/>, sean, <b/>, <c/>, <d/>
-
1
def each( xpath=nil, &block)
-
183
XPath::each( @element, xpath ) {|e| yield e if e.kind_of? Element }
-
end
-
-
1
def collect( xpath=nil, &block )
-
collection = []
-
XPath::each( @element, xpath ) {|e|
-
collection << yield(e) if e.kind_of?(Element)
-
}
-
collection
-
end
-
-
1
def inject( xpath=nil, initial=nil, &block )
-
first = true
-
XPath::each( @element, xpath ) {|e|
-
if (e.kind_of? Element)
-
if (first and initial == nil)
-
initial = e
-
first = false
-
else
-
initial = yield( initial, e ) if e.kind_of? Element
-
end
-
end
-
}
-
initial
-
end
-
-
# Returns the number of +Element+ children of the parent object.
-
# doc = Document.new '<a>sean<b/>elliott<b/>russell<b/></a>'
-
# doc.root.size #-> 6, 3 element and 3 text nodes
-
# doc.root.elements.size #-> 3
-
1
def size
-
199
count = 0
-
602
@element.each {|child| count+=1 if child.kind_of? Element }
-
199
count
-
end
-
-
# Returns an Array of Element children. An XPath may be supplied to
-
# filter the children. Only Element children are returned, even if the
-
# supplied XPath matches non-Element children.
-
# doc = Document.new '<a>sean<b/>elliott<c/></a>'
-
# doc.root.elements.to_a #-> [ <b/>, <c/> ]
-
# doc.root.elements.to_a("child::node()") #-> [ <b/>, <c/> ]
-
# XPath.match(doc.root, "child::node()") #-> [ sean, <b/>, elliott, <c/> ]
-
1
def to_a( xpath=nil )
-
rv = XPath.match( @element, xpath )
-
return rv.find_all{|e| e.kind_of? Element} if xpath
-
rv
-
end
-
-
1
private
-
# Private helper class. Removes quotes from quoted strings
-
1
def literalize name
-
name = name[1..-2] if name[0] == ?' or name[0] == ?" #'
-
name
-
end
-
end
-
-
########################################################################
-
# ATTRIBUTES #
-
########################################################################
-
-
# A class that defines the set of Attributes of an Element and provides
-
# operations for accessing elements in that set.
-
1
class Attributes < Hash
-
# Constructor
-
# element:: the Element of which this is an Attribute
-
1
def initialize element
-
231
@element = element
-
end
-
-
# Fetches an attribute value. If you want to get the Attribute itself,
-
# use get_attribute()
-
# name:: an XPath attribute name. Namespaces are relevant here.
-
# Returns::
-
# the String value of the matching attribute, or +nil+ if no
-
# matching attribute was found. This is the unnormalized value
-
# (with entities expanded).
-
#
-
# doc = Document.new "<a foo:att='1' bar:att='2' att='<'/>"
-
# doc.root.attributes['att'] #-> '<'
-
# doc.root.attributes['bar:att'] #-> '2'
-
1
def [](name)
-
attr = get_attribute(name)
-
return attr.value unless attr.nil?
-
return nil
-
end
-
-
1
def to_a
-
values.flatten
-
end
-
-
# Returns the number of attributes the owning Element contains.
-
# doc = Document "<a x='1' y='2' foo:x='3'/>"
-
# doc.root.attributes.length #-> 3
-
1
def length
-
c = 0
-
each_attribute { c+=1 }
-
c
-
end
-
1
alias :size :length
-
-
# Iterates over the attributes of an Element. Yields actual Attribute
-
# nodes, not String values.
-
#
-
# doc = Document.new '<a x="1" y="2"/>'
-
# doc.root.attributes.each_attribute {|attr|
-
# p attr.expanded_name+" => "+attr.value
-
# }
-
1
def each_attribute # :yields: attribute
-
180
each_value do |val|
-
103
if val.kind_of? Attribute
-
103
yield val
-
else
-
val.each_value { |atr| yield atr }
-
end
-
end
-
end
-
-
# Iterates over each attribute of an Element, yielding the expanded name
-
# and value as a pair of Strings.
-
#
-
# doc = Document.new '<a x="1" y="2"/>'
-
# doc.root.attributes.each {|name, value| p name+" => "+value }
-
1
def each
-
180
each_attribute do |attr|
-
103
yield [attr.expanded_name, attr.value]
-
end
-
end
-
-
# Fetches an attribute
-
# name::
-
# the name by which to search for the attribute. Can be a
-
# <tt>prefix:name</tt> namespace name.
-
# Returns:: The first matching attribute, or nil if there was none. This
-
# value is an Attribute node, not the String value of the attribute.
-
# doc = Document.new '<a x:foo="1" foo="2" bar="3"/>'
-
# doc.root.attributes.get_attribute("foo").value #-> "2"
-
# doc.root.attributes.get_attribute("x:foo").value #-> "1"
-
1
def get_attribute( name )
-
attr = fetch( name, nil )
-
if attr.nil?
-
return nil if name.nil?
-
# Look for prefix
-
name =~ Namespace::NAMESPLIT
-
prefix, n = $1, $2
-
if prefix
-
attr = fetch( n, nil )
-
# check prefix
-
if attr == nil
-
elsif attr.kind_of? Attribute
-
return attr if prefix == attr.prefix
-
else
-
attr = attr[ prefix ]
-
return attr
-
end
-
end
-
element_document = @element.document
-
if element_document and element_document.doctype
-
expn = @element.expanded_name
-
expn = element_document.doctype.name if expn.size == 0
-
attr_val = element_document.doctype.attribute_of(expn, name)
-
return Attribute.new( name, attr_val ) if attr_val
-
end
-
return nil
-
end
-
if attr.kind_of? Hash
-
attr = attr[ @element.prefix ]
-
end
-
return attr
-
end
-
-
# Sets an attribute, overwriting any existing attribute value by the
-
# same name. Namespace is significant.
-
# name:: the name of the attribute
-
# value::
-
# (optional) If supplied, the value of the attribute. If
-
# nil, any existing matching attribute is deleted.
-
# Returns::
-
# Owning element
-
# doc = Document.new "<a x:foo='1' foo='3'/>"
-
# doc.root.attributes['y:foo'] = '2'
-
# doc.root.attributes['foo'] = '4'
-
# doc.root.attributes['x:foo'] = nil
-
1
def []=( name, value )
-
103
if value.nil? # Delete the named attribute
-
attr = get_attribute(name)
-
delete attr
-
return
-
end
-
-
103
unless value.kind_of? Attribute
-
if @element.document and @element.document.doctype
-
value = Text::normalize( value, @element.document.doctype )
-
else
-
value = Text::normalize( value, nil )
-
end
-
value = Attribute.new(name, value)
-
end
-
103
value.element = @element
-
103
old_attr = fetch(value.name, nil)
-
103
if old_attr.nil?
-
103
store(value.name, value)
-
elsif old_attr.kind_of? Hash
-
old_attr[value.prefix] = value
-
elsif old_attr.prefix != value.prefix
-
# Check for conflicting namespaces
-
raise ParseException.new(
-
"Namespace conflict in adding attribute \"#{value.name}\": "+
-
"Prefix \"#{old_attr.prefix}\" = "+
-
"\"#{@element.namespace(old_attr.prefix)}\" and prefix "+
-
"\"#{value.prefix}\" = \"#{@element.namespace(value.prefix)}\"") if
-
value.prefix != "xmlns" and old_attr.prefix != "xmlns" and
-
@element.namespace( old_attr.prefix ) ==
-
@element.namespace( value.prefix )
-
store value.name, { old_attr.prefix => old_attr,
-
value.prefix => value }
-
else
-
store value.name, value
-
end
-
103
return @element
-
end
-
-
# Returns an array of Strings containing all of the prefixes declared
-
# by this set of # attributes. The array does not include the default
-
# namespace declaration, if one exists.
-
# doc = Document.new("<a xmlns='foo' xmlns:x='bar' xmlns:y='twee' "+
-
# "z='glorp' p:k='gru'/>")
-
# prefixes = doc.root.attributes.prefixes #-> ['x', 'y']
-
1
def prefixes
-
ns = []
-
each_attribute do |attribute|
-
ns << attribute.name if attribute.prefix == 'xmlns'
-
end
-
if @element.document and @element.document.doctype
-
expn = @element.expanded_name
-
expn = @element.document.doctype.name if expn.size == 0
-
@element.document.doctype.attributes_of(expn).each {
-
|attribute|
-
ns << attribute.name if attribute.prefix == 'xmlns'
-
}
-
end
-
ns
-
end
-
-
1
def namespaces
-
namespaces = {}
-
each_attribute do |attribute|
-
namespaces[attribute.name] = attribute.value if attribute.prefix == 'xmlns' or attribute.name == 'xmlns'
-
end
-
if @element.document and @element.document.doctype
-
expn = @element.expanded_name
-
expn = @element.document.doctype.name if expn.size == 0
-
@element.document.doctype.attributes_of(expn).each {
-
|attribute|
-
namespaces[attribute.name] = attribute.value if attribute.prefix == 'xmlns' or attribute.name == 'xmlns'
-
}
-
end
-
namespaces
-
end
-
-
# Removes an attribute
-
# attribute::
-
# either a String, which is the name of the attribute to remove --
-
# namespaces are significant here -- or the attribute to remove.
-
# Returns:: the owning element
-
# doc = Document.new "<a y:foo='0' x:foo='1' foo='3' z:foo='4'/>"
-
# doc.root.attributes.delete 'foo' #-> <a y:foo='0' x:foo='1' z:foo='4'/>"
-
# doc.root.attributes.delete 'x:foo' #-> <a y:foo='0' z:foo='4'/>"
-
# attr = doc.root.attributes.get_attribute('y:foo')
-
# doc.root.attributes.delete attr #-> <a z:foo='4'/>"
-
1
def delete( attribute )
-
name = nil
-
prefix = nil
-
if attribute.kind_of? Attribute
-
name = attribute.name
-
prefix = attribute.prefix
-
else
-
attribute =~ Namespace::NAMESPLIT
-
prefix, name = $1, $2
-
prefix = '' unless prefix
-
end
-
old = fetch(name, nil)
-
attr = nil
-
if old.kind_of? Hash # the supplied attribute is one of many
-
attr = old.delete(prefix)
-
if old.size == 1
-
repl = nil
-
old.each_value{|v| repl = v}
-
store name, repl
-
end
-
elsif old.nil?
-
return @element
-
else # the supplied attribute is a top-level one
-
attr = old
-
super(name)
-
end
-
@element
-
end
-
-
# Adds an attribute, overriding any existing attribute by the
-
# same name. Namespaces are significant.
-
# attribute:: An Attribute
-
1
def add( attribute )
-
self[attribute.name] = attribute
-
end
-
-
1
alias :<< :add
-
-
# Deletes all attributes matching a name. Namespaces are significant.
-
# name::
-
# A String; all attributes that match this path will be removed
-
# Returns:: an Array of the Attributes that were removed
-
1
def delete_all( name )
-
rv = []
-
each_attribute { |attribute|
-
rv << attribute if attribute.expanded_name == name
-
}
-
rv.each{ |attr| attr.remove }
-
return rv
-
end
-
-
# The +get_attribute_ns+ method retrieves a method by its namespace
-
# and name. Thus it is possible to reliably identify an attribute
-
# even if an XML processor has changed the prefix.
-
#
-
# Method contributed by Henrik Martensson
-
1
def get_attribute_ns(namespace, name)
-
result = nil
-
each_attribute() { |attribute|
-
if name == attribute.name &&
-
namespace == attribute.namespace() &&
-
( !namespace.empty? || !attribute.fully_expanded_name.index(':') )
-
# foo will match xmlns:foo, but only if foo isn't also an attribute
-
result = attribute if !result or !namespace.empty? or
-
!attribute.fully_expanded_name.index(':')
-
end
-
}
-
result
-
end
-
end
-
end
-
1
module REXML
-
1
module Encoding
-
# ID ---> Encoding name
-
1
attr_reader :encoding
-
1
def encoding=(encoding)
-
54
encoding = encoding.name if encoding.is_a?(Encoding)
-
54
if encoding.is_a?(String)
-
54
original_encoding = encoding
-
54
encoding = find_encoding(encoding)
-
54
unless encoding
-
raise ArgumentError, "Bad encoding name #{original_encoding}"
-
end
-
end
-
54
return false if defined?(@encoding) and encoding == @encoding
-
53
if encoding
-
53
@encoding = encoding.upcase
-
else
-
@encoding = 'UTF-8'
-
end
-
53
true
-
end
-
-
1
def check_encoding(xml)
-
# We have to recognize UTF-16BE, UTF-16LE, and UTF-8
-
51
if xml[0, 2] == "\xfe\xff"
-
xml[0, 2] = ""
-
return 'UTF-16BE'
-
elsif xml[0, 2] == "\xff\xfe"
-
xml[0, 2] = ""
-
return 'UTF-16LE'
-
end
-
51
xml =~ /^\s*<\?xml\s+version\s*=\s*(['"]).*?\1\s+encoding\s*=\s*(["'])(.*?)\2/m
-
51
return $3 ? $3.upcase : 'UTF-8'
-
end
-
-
1
def encode(string)
-
51
string.encode(@encoding)
-
end
-
-
1
def decode(string)
-
string.encode(::Encoding::UTF_8, @encoding)
-
end
-
-
1
private
-
1
def find_encoding(name)
-
54
case name
-
when /\Ashift-jis\z/i
-
return "SHIFT_JIS"
-
when /\ACP-(\d+)\z/
-
name = "CP#{$1}"
-
when /\AUTF-8\z/i
-
54
return name
-
end
-
begin
-
::Encoding::Converter.search_convpath(name, 'UTF-8')
-
rescue ::Encoding::ConverterNotFoundError
-
return nil
-
end
-
name
-
end
-
end
-
end
-
1
require 'rexml/child'
-
1
require 'rexml/source'
-
1
require 'rexml/xmltokens'
-
-
1
module REXML
-
# God, I hate DTDs. I really do. Why this idiot standard still
-
# plagues us is beyond me.
-
1
class Entity < Child
-
1
include XMLTokens
-
1
PUBIDCHAR = "\x20\x0D\x0Aa-zA-Z0-9\\-()+,./:=?;!*@$_%#"
-
1
SYSTEMLITERAL = %Q{((?:"[^"]*")|(?:'[^']*'))}
-
1
PUBIDLITERAL = %Q{("[#{PUBIDCHAR}']*"|'[#{PUBIDCHAR}]*')}
-
1
EXTERNALID = "(?:(?:(SYSTEM)\\s+#{SYSTEMLITERAL})|(?:(PUBLIC)\\s+#{PUBIDLITERAL}\\s+#{SYSTEMLITERAL}))"
-
1
NDATADECL = "\\s+NDATA\\s+#{NAME}"
-
1
PEREFERENCE = "%#{NAME};"
-
1
ENTITYVALUE = %Q{((?:"(?:[^%&"]|#{PEREFERENCE}|#{REFERENCE})*")|(?:'([^%&']|#{PEREFERENCE}|#{REFERENCE})*'))}
-
1
PEDEF = "(?:#{ENTITYVALUE}|#{EXTERNALID})"
-
1
ENTITYDEF = "(?:#{ENTITYVALUE}|(?:#{EXTERNALID}(#{NDATADECL})?))"
-
1
PEDECL = "<!ENTITY\\s+(%)\\s+#{NAME}\\s+#{PEDEF}\\s*>"
-
1
GEDECL = "<!ENTITY\\s+#{NAME}\\s+#{ENTITYDEF}\\s*>"
-
1
ENTITYDECL = /\s*(?:#{GEDECL})|(?:#{PEDECL})/um
-
-
1
attr_reader :name, :external, :ref, :ndata, :pubid
-
-
# Create a new entity. Simple entities can be constructed by passing a
-
# name, value to the constructor; this creates a generic, plain entity
-
# reference. For anything more complicated, you have to pass a Source to
-
# the constructor with the entity definition, or use the accessor methods.
-
# +WARNING+: There is no validation of entity state except when the entity
-
# is read from a stream. If you start poking around with the accessors,
-
# you can easily create a non-conformant Entity. The best thing to do is
-
# dump the stupid DTDs and use XMLSchema instead.
-
#
-
# e = Entity.new( 'amp', '&' )
-
1
def initialize stream, value=nil, parent=nil, reference=false
-
12
super(parent)
-
12
@ndata = @pubid = @value = @external = nil
-
12
if stream.kind_of? Array
-
7
@name = stream[1]
-
7
if stream[-1] == '%'
-
@reference = true
-
stream.pop
-
else
-
7
@reference = false
-
end
-
7
if stream[2] =~ /SYSTEM|PUBLIC/
-
@external = stream[2]
-
if @external == 'SYSTEM'
-
@ref = stream[3]
-
@ndata = stream[4] if stream.size == 5
-
else
-
@pubid = stream[3]
-
@ref = stream[4]
-
end
-
else
-
7
@value = stream[2]
-
end
-
else
-
5
@reference = reference
-
5
@external = nil
-
5
@name = stream
-
5
@value = value
-
end
-
end
-
-
# Evaluates whether the given string matchs an entity definition,
-
# returning true if so, and false otherwise.
-
1
def Entity::matches? string
-
(ENTITYDECL =~ string) == 0
-
end
-
-
# Evaluates to the unnormalized value of this entity; that is, replacing
-
# all entities -- both %ent; and &ent; entities. This differs from
-
# +value()+ in that +value+ only replaces %ent; entities.
-
1
def unnormalized
-
10001
document.record_entity_expansion unless document.nil?
-
10000
v = value()
-
10000
return nil if v.nil?
-
10000
@unnormalized = Text::unnormalize(v, parent)
-
9994
@unnormalized
-
end
-
-
#once :unnormalized
-
-
# Returns the value of this entity unprocessed -- raw. This is the
-
# normalized value; that is, with all %ent; and &ent; entities intact
-
1
def normalized
-
@value
-
end
-
-
# Write out a fully formed, correct entity definition (assuming the Entity
-
# object itself is valid.)
-
#
-
# out::
-
# An object implementing <TT><<<TT> to which the entity will be
-
# output
-
# indent::
-
# *DEPRECATED* and ignored
-
1
def write out, indent=-1
-
out << '<!ENTITY '
-
out << '% ' if @reference
-
out << @name
-
out << ' '
-
if @external
-
out << @external << ' '
-
if @pubid
-
q = @pubid.include?('"')?"'":'"'
-
out << q << @pubid << q << ' '
-
end
-
q = @ref.include?('"')?"'":'"'
-
out << q << @ref << q
-
out << ' NDATA ' << @ndata if @ndata
-
else
-
q = @value.include?('"')?"'":'"'
-
out << q << @value << q
-
end
-
out << '>'
-
end
-
-
# Returns this entity as a string. See write().
-
1
def to_s
-
rv = ''
-
write rv
-
rv
-
end
-
-
1
PEREFERENCE_RE = /#{PEREFERENCE}/um
-
# Returns the value of this entity. At the moment, only internal entities
-
# are processed. If the value contains internal references (IE,
-
# %blah;), those are replaced with their values. IE, if the doctype
-
# contains:
-
# <!ENTITY % foo "bar">
-
# <!ENTITY yada "nanoo %foo; nanoo>
-
# then:
-
# doctype.entity('yada').value #-> "nanoo bar nanoo"
-
1
def value
-
10007
if @value
-
10007
matches = @value.scan(PEREFERENCE_RE)
-
10007
rv = @value.clone
-
10007
if @parent
-
10007
matches.each do |entity_reference|
-
entity_value = @parent.entity( entity_reference[0] )
-
rv.gsub!( /%#{entity_reference.join};/um, entity_value )
-
end
-
end
-
10007
return rv
-
end
-
nil
-
end
-
end
-
-
# This is a set of entity constants -- the ones defined in the XML
-
# specification. These are +gt+, +lt+, +amp+, +quot+ and +apos+.
-
1
module EntityConst
-
# +>+
-
1
GT = Entity.new( 'gt', '>' )
-
# +<+
-
1
LT = Entity.new( 'lt', '<' )
-
# +&+
-
1
AMP = Entity.new( 'amp', '&' )
-
# +"+
-
1
QUOT = Entity.new( 'quot', '"' )
-
# +'+
-
1
APOS = Entity.new( 'apos', "'" )
-
end
-
end
-
1
module REXML
-
1
module Formatters
-
1
class Default
-
# Prints out the XML document with no formatting -- except if id_hack is
-
# set.
-
#
-
# ie_hack::
-
# If set to true, then inserts whitespace before the close of an empty
-
# tag, so that IE's bad XML parser doesn't choke.
-
1
def initialize( ie_hack=false )
-
@ie_hack = ie_hack
-
end
-
-
# Writes the node to some output.
-
#
-
# node::
-
# The node to write
-
# output::
-
# A class implementing <TT><<</TT>. Pass in an Output object to
-
# change the output encoding.
-
1
def write( node, output )
-
case node
-
-
when Document
-
if node.xml_decl.encoding != 'UTF-8' && !output.kind_of?(Output)
-
output = Output.new( output, node.xml_decl.encoding )
-
end
-
write_document( node, output )
-
-
when Element
-
write_element( node, output )
-
-
when Declaration, ElementDecl, NotationDecl, ExternalEntity, Entity,
-
Attribute, AttlistDecl
-
node.write( output,-1 )
-
-
when Instruction
-
write_instruction( node, output )
-
-
when DocType, XMLDecl
-
node.write( output )
-
-
when Comment
-
write_comment( node, output )
-
-
when CData
-
write_cdata( node, output )
-
-
when Text
-
write_text( node, output )
-
-
else
-
raise Exception.new("XML FORMATTING ERROR")
-
-
end
-
end
-
-
1
protected
-
1
def write_document( node, output )
-
node.children.each { |child| write( child, output ) }
-
end
-
-
1
def write_element( node, output )
-
output << "<#{node.expanded_name}"
-
-
node.attributes.to_a.map { |a|
-
Hash === a ? a.values : a
-
}.flatten.sort_by {|attr| attr.name}.each do |attr|
-
output << " "
-
attr.write( output )
-
end unless node.attributes.empty?
-
-
if node.children.empty?
-
output << " " if @ie_hack
-
output << "/"
-
else
-
output << ">"
-
node.children.each { |child|
-
write( child, output )
-
}
-
output << "</#{node.expanded_name}"
-
end
-
output << ">"
-
end
-
-
1
def write_text( node, output )
-
output << node.to_s()
-
end
-
-
1
def write_comment( node, output )
-
output << Comment::START
-
output << node.to_s
-
output << Comment::STOP
-
end
-
-
1
def write_cdata( node, output )
-
output << CData::START
-
output << node.to_s
-
output << CData::STOP
-
end
-
-
1
def write_instruction( node, output )
-
output << Instruction::START.sub(/\\/u, '')
-
output << node.target
-
output << ' '
-
output << node.content
-
output << Instruction::STOP.sub(/\\/u, '')
-
end
-
end
-
end
-
end
-
1
require 'rexml/formatters/default'
-
-
1
module REXML
-
1
module Formatters
-
# Pretty-prints an XML document. This destroys whitespace in text nodes
-
# and will insert carriage returns and indentations.
-
#
-
# TODO: Add an option to print attributes on new lines
-
1
class Pretty < Default
-
-
# If compact is set to true, then the formatter will attempt to use as
-
# little space as possible
-
1
attr_accessor :compact
-
# The width of a page. Used for formatting text
-
1
attr_accessor :width
-
-
# Create a new pretty printer.
-
#
-
# output::
-
# An object implementing '<<(String)', to which the output will be written.
-
# indentation::
-
# An integer greater than 0. The indentation of each level will be
-
# this number of spaces. If this is < 1, the behavior of this object
-
# is undefined. Defaults to 2.
-
# ie_hack::
-
# If true, the printer will insert whitespace before closing empty
-
# tags, thereby allowing Internet Explorer's feeble XML parser to
-
# function. Defaults to false.
-
1
def initialize( indentation=2, ie_hack=false )
-
@indentation = indentation
-
@level = 0
-
@ie_hack = ie_hack
-
@width = 80
-
@compact = false
-
end
-
-
1
protected
-
1
def write_element(node, output)
-
output << ' '*@level
-
output << "<#{node.expanded_name}"
-
-
node.attributes.each_attribute do |attr|
-
output << " "
-
attr.write( output )
-
end unless node.attributes.empty?
-
-
if node.children.empty?
-
if @ie_hack
-
output << " "
-
end
-
output << "/"
-
else
-
output << ">"
-
# If compact and all children are text, and if the formatted output
-
# is less than the specified width, then try to print everything on
-
# one line
-
skip = false
-
if compact
-
if node.children.inject(true) {|s,c| s & c.kind_of?(Text)}
-
string = ""
-
old_level = @level
-
@level = 0
-
node.children.each { |child| write( child, string ) }
-
@level = old_level
-
if string.length < @width
-
output << string
-
skip = true
-
end
-
end
-
end
-
unless skip
-
output << "\n"
-
@level += @indentation
-
node.children.each { |child|
-
next if child.kind_of?(Text) and child.to_s.strip.length == 0
-
write( child, output )
-
output << "\n"
-
}
-
@level -= @indentation
-
output << ' '*@level
-
end
-
output << "</#{node.expanded_name}"
-
end
-
output << ">"
-
end
-
-
1
def write_text( node, output )
-
s = node.to_s()
-
s.gsub!(/\s/,' ')
-
s.squeeze!(" ")
-
s = wrap(s, @width - @level)
-
s = indent_text(s, @level, " ", true)
-
output << (' '*@level + s)
-
end
-
-
1
def write_comment( node, output)
-
output << ' ' * @level
-
super
-
end
-
-
1
def write_cdata( node, output)
-
output << ' ' * @level
-
super
-
end
-
-
1
def write_document( node, output )
-
# Ok, this is a bit odd. All XML documents have an XML declaration,
-
# but it may not write itself if the user didn't specifically add it,
-
# either through the API or in the input document. If it doesn't write
-
# itself, then we don't need a carriage return... which makes this
-
# logic more complex.
-
node.children.each { |child|
-
next if child == node.children[-1] and child.instance_of?(Text)
-
unless child == node.children[0] or child.instance_of?(Text) or
-
(child == node.children[1] and !node.children[0].writethis)
-
output << "\n"
-
end
-
write( child, output )
-
}
-
end
-
-
1
private
-
1
def indent_text(string, level=1, style="\t", indentfirstline=true)
-
return string if level < 0
-
string.gsub(/\n/, "\n#{style*level}")
-
end
-
-
1
def wrap(string, width)
-
parts = []
-
while string.length > width and place = string.rindex(' ', width)
-
parts << string[0...place]
-
string = string[place+1..-1]
-
end
-
parts << string
-
parts.join("\n")
-
end
-
-
end
-
end
-
end
-
-
1
module REXML
-
# If you add a method, keep in mind two things:
-
# (1) the first argument will always be a list of nodes from which to
-
# filter. In the case of context methods (such as position), the function
-
# should return an array with a value for each child in the array.
-
# (2) all method calls from XML will have "-" replaced with "_".
-
# Therefore, in XML, "local-name()" is identical (and actually becomes)
-
# "local_name()"
-
1
module Functions
-
1
@@context = nil
-
1
@@namespace_context = {}
-
1
@@variables = {}
-
-
55
def Functions::namespace_context=(x) ; @@namespace_context=x ; end
-
55
def Functions::variables=(x) ; @@variables=x ; end
-
1
def Functions::namespace_context ; @@namespace_context ; end
-
1
def Functions::variables ; @@variables ; end
-
-
1
def Functions::context=(value); @@context = value; end
-
-
1
def Functions::text( )
-
if @@context[:node].node_type == :element
-
return @@context[:node].find_all{|n| n.node_type == :text}.collect{|n| n.value}
-
elsif @@context[:node].node_type == :text
-
return @@context[:node].value
-
else
-
return false
-
end
-
end
-
-
# Returns the last node of the given list of nodes.
-
1
def Functions::last( )
-
@@context[:size]
-
end
-
-
1
def Functions::position( )
-
@@context[:index]
-
end
-
-
# Returns the size of the given list of nodes.
-
1
def Functions::count( node_set )
-
node_set.size
-
end
-
-
# Since REXML is non-validating, this method is not implemented as it
-
# requires a DTD
-
1
def Functions::id( object )
-
end
-
-
# UNTESTED
-
1
def Functions::local_name( node_set=nil )
-
get_namespace( node_set ) do |node|
-
return node.local_name
-
end
-
end
-
-
1
def Functions::namespace_uri( node_set=nil )
-
get_namespace( node_set ) {|node| node.namespace}
-
end
-
-
1
def Functions::name( node_set=nil )
-
get_namespace( node_set ) do |node|
-
node.expanded_name
-
end
-
end
-
-
# Helper method.
-
1
def Functions::get_namespace( node_set = nil )
-
if node_set == nil
-
yield @@context[:node] if defined? @@context[:node].namespace
-
else
-
if node_set.respond_to? :each
-
node_set.each { |node| yield node if defined? node.namespace }
-
elsif node_set.respond_to? :namespace
-
yield node_set
-
end
-
end
-
end
-
-
# A node-set is converted to a string by returning the string-value of the
-
# node in the node-set that is first in document order. If the node-set is
-
# empty, an empty string is returned.
-
#
-
# A number is converted to a string as follows
-
#
-
# NaN is converted to the string NaN
-
#
-
# positive zero is converted to the string 0
-
#
-
# negative zero is converted to the string 0
-
#
-
# positive infinity is converted to the string Infinity
-
#
-
# negative infinity is converted to the string -Infinity
-
#
-
# if the number is an integer, the number is represented in decimal form
-
# as a Number with no decimal point and no leading zeros, preceded by a
-
# minus sign (-) if the number is negative
-
#
-
# otherwise, the number is represented in decimal form as a Number
-
# including a decimal point with at least one digit before the decimal
-
# point and at least one digit after the decimal point, preceded by a
-
# minus sign (-) if the number is negative; there must be no leading zeros
-
# before the decimal point apart possibly from the one required digit
-
# immediately before the decimal point; beyond the one required digit
-
# after the decimal point there must be as many, but only as many, more
-
# digits as are needed to uniquely distinguish the number from all other
-
# IEEE 754 numeric values.
-
#
-
# The boolean false value is converted to the string false. The boolean
-
# true value is converted to the string true.
-
#
-
# An object of a type other than the four basic types is converted to a
-
# string in a way that is dependent on that type.
-
1
def Functions::string( object=nil )
-
#object = @context unless object
-
if object.instance_of? Array
-
string( object[0] )
-
elsif defined? object.node_type
-
if object.node_type == :attribute
-
object.value
-
elsif object.node_type == :element || object.node_type == :document
-
string_value(object)
-
else
-
object.to_s
-
end
-
elsif object.nil?
-
return ""
-
else
-
object.to_s
-
end
-
end
-
-
# A node-set is converted to a string by
-
# returning the concatenation of the string-value
-
# of each of the children of the node in the
-
# node-set that is first in document order.
-
# If the node-set is empty, an empty string is returned.
-
1
def Functions::string_value( o )
-
rv = ""
-
o.children.each { |e|
-
if e.node_type == :text
-
rv << e.to_s
-
elsif e.node_type == :element
-
rv << string_value( e )
-
end
-
}
-
rv
-
end
-
-
# UNTESTED
-
1
def Functions::concat( *objects )
-
objects.join
-
end
-
-
# Fixed by Mike Stok
-
1
def Functions::starts_with( string, test )
-
string(string).index(string(test)) == 0
-
end
-
-
# Fixed by Mike Stok
-
1
def Functions::contains( string, test )
-
string(string).include?(string(test))
-
end
-
-
# Kouhei fixed this
-
1
def Functions::substring_before( string, test )
-
ruby_string = string(string)
-
ruby_index = ruby_string.index(string(test))
-
if ruby_index.nil?
-
""
-
else
-
ruby_string[ 0...ruby_index ]
-
end
-
end
-
-
# Kouhei fixed this too
-
1
def Functions::substring_after( string, test )
-
ruby_string = string(string)
-
return $1 if ruby_string =~ /#{test}(.*)/
-
""
-
end
-
-
# Take equal portions of Mike Stok and Sean Russell; mix
-
# vigorously, and pour into a tall, chilled glass. Serves 10,000.
-
1
def Functions::substring( string, start, length=nil )
-
ruby_string = string(string)
-
ruby_length = if length.nil?
-
ruby_string.length.to_f
-
else
-
number(length)
-
end
-
ruby_start = number(start)
-
-
# Handle the special cases
-
return '' if (
-
ruby_length.nan? or
-
ruby_start.nan? or
-
ruby_start.infinite?
-
)
-
-
infinite_length = ruby_length.infinite? == 1
-
ruby_length = ruby_string.length if infinite_length
-
-
# Now, get the bounds. The XPath bounds are 1..length; the ruby bounds
-
# are 0..length. Therefore, we have to offset the bounds by one.
-
ruby_start = ruby_start.round - 1
-
ruby_length = ruby_length.round
-
-
if ruby_start < 0
-
ruby_length += ruby_start unless infinite_length
-
ruby_start = 0
-
end
-
return '' if ruby_length <= 0
-
ruby_string[ruby_start,ruby_length]
-
end
-
-
# UNTESTED
-
1
def Functions::string_length( string )
-
string(string).length
-
end
-
-
# UNTESTED
-
1
def Functions::normalize_space( string=nil )
-
string = string(@@context[:node]) if string.nil?
-
if string.kind_of? Array
-
string.collect{|x| string.to_s.strip.gsub(/\s+/um, ' ') if string}
-
else
-
string.to_s.strip.gsub(/\s+/um, ' ')
-
end
-
end
-
-
# This is entirely Mike Stok's beast
-
1
def Functions::translate( string, tr1, tr2 )
-
from = string(tr1)
-
to = string(tr2)
-
-
# the map is our translation table.
-
#
-
# if a character occurs more than once in the
-
# from string then we ignore the second &
-
# subsequent mappings
-
#
-
# if a character maps to nil then we delete it
-
# in the output. This happens if the from
-
# string is longer than the to string
-
#
-
# there's nothing about - or ^ being special in
-
# http://www.w3.org/TR/xpath#function-translate
-
# so we don't build ranges or negated classes
-
-
map = Hash.new
-
0.upto(from.length - 1) { |pos|
-
from_char = from[pos]
-
unless map.has_key? from_char
-
map[from_char] =
-
if pos < to.length
-
to[pos]
-
else
-
nil
-
end
-
end
-
}
-
-
if ''.respond_to? :chars
-
string(string).chars.collect { |c|
-
if map.has_key? c then map[c] else c end
-
}.compact.join
-
else
-
string(string).unpack('U*').collect { |c|
-
if map.has_key? c then map[c] else c end
-
}.compact.pack('U*')
-
end
-
end
-
-
# UNTESTED
-
1
def Functions::boolean( object=nil )
-
if object.kind_of? String
-
if object =~ /\d+/u
-
return object.to_f != 0
-
else
-
return object.size > 0
-
end
-
elsif object.kind_of? Array
-
object = object.find{|x| x and true}
-
end
-
return object ? true : false
-
end
-
-
# UNTESTED
-
1
def Functions::not( object )
-
not boolean( object )
-
end
-
-
# UNTESTED
-
1
def Functions::true( )
-
true
-
end
-
-
# UNTESTED
-
1
def Functions::false( )
-
false
-
end
-
-
# UNTESTED
-
1
def Functions::lang( language )
-
lang = false
-
node = @@context[:node]
-
attr = nil
-
until node.nil?
-
if node.node_type == :element
-
attr = node.attributes["xml:lang"]
-
unless attr.nil?
-
lang = compare_language(string(language), attr)
-
break
-
else
-
end
-
end
-
node = node.parent
-
end
-
lang
-
end
-
-
1
def Functions::compare_language lang1, lang2
-
lang2.downcase.index(lang1.downcase) == 0
-
end
-
-
# a string that consists of optional whitespace followed by an optional
-
# minus sign followed by a Number followed by whitespace is converted to
-
# the IEEE 754 number that is nearest (according to the IEEE 754
-
# round-to-nearest rule) to the mathematical value represented by the
-
# string; any other string is converted to NaN
-
#
-
# boolean true is converted to 1; boolean false is converted to 0
-
#
-
# a node-set is first converted to a string as if by a call to the string
-
# function and then converted in the same way as a string argument
-
#
-
# an object of a type other than the four basic types is converted to a
-
# number in a way that is dependent on that type
-
1
def Functions::number( object=nil )
-
object = @@context[:node] unless object
-
case object
-
when true
-
Float(1)
-
when false
-
Float(0)
-
when Array
-
number(string( object ))
-
when Numeric
-
object.to_f
-
else
-
str = string( object )
-
# If XPath ever gets scientific notation...
-
#if str =~ /^\s*-?(\d*\.?\d+|\d+\.)([Ee]\d*)?\s*$/
-
if str =~ /^\s*-?(\d*\.?\d+|\d+\.)\s*$/
-
str.to_f
-
else
-
(0.0 / 0.0)
-
end
-
end
-
end
-
-
1
def Functions::sum( nodes )
-
nodes = [nodes] unless nodes.kind_of? Array
-
nodes.inject(0) { |r,n| r += number(string(n)) }
-
end
-
-
1
def Functions::floor( number )
-
number(number).floor
-
end
-
-
1
def Functions::ceiling( number )
-
number(number).ceil
-
end
-
-
1
def Functions::round( number )
-
begin
-
number(number).round
-
rescue FloatDomainError
-
number(number)
-
end
-
end
-
-
1
def Functions::processing_instruction( node )
-
node.node_type == :processing_instruction
-
end
-
-
1
def Functions::method_missing( id )
-
puts "METHOD MISSING #{id.id2name}"
-
XPath.match( @@context[:node], id.id2name )
-
end
-
end
-
end
-
1
require "rexml/child"
-
1
require "rexml/source"
-
-
1
module REXML
-
# Represents an XML Instruction; IE, <? ... ?>
-
# TODO: Add parent arg (3rd arg) to constructor
-
1
class Instruction < Child
-
1
START = '<\?'
-
1
STOP = '\?>'
-
-
# target is the "name" of the Instruction; IE, the "tag" in <?tag ...?>
-
# content is everything else.
-
1
attr_accessor :target, :content
-
-
# Constructs a new Instruction
-
# @param target can be one of a number of things. If String, then
-
# the target of this instruction is set to this. If an Instruction,
-
# then the Instruction is shallowly cloned (target and content are
-
# copied). If a Source, then the source is scanned and parsed for
-
# an Instruction declaration.
-
# @param content Must be either a String, or a Parent. Can only
-
# be a Parent if the target argument is a Source. Otherwise, this
-
# String is set as the content of this instruction.
-
1
def initialize(target, content=nil)
-
if target.kind_of? String
-
super()
-
@target = target
-
@content = content
-
elsif target.kind_of? Instruction
-
super(content)
-
@target = target.target
-
@content = target.content
-
end
-
@content.strip! if @content
-
end
-
-
1
def clone
-
Instruction.new self
-
end
-
-
# == DEPRECATED
-
# See the rexml/formatters package
-
#
-
1
def write writer, indent=-1, transitive=false, ie_hack=false
-
Kernel.warn( "#{self.class.name}.write is deprecated" )
-
indent(writer, indent)
-
writer << START.sub(/\\/u, '')
-
writer << @target
-
writer << ' '
-
writer << @content
-
writer << STOP.sub(/\\/u, '')
-
end
-
-
# @return true if other is an Instruction, and the content and target
-
# of the other matches the target and content of this object.
-
1
def ==( other )
-
other.kind_of? Instruction and
-
other.target == @target and
-
other.content == @content
-
end
-
-
1
def node_type
-
:processing_instruction
-
end
-
-
1
def inspect
-
"<?p-i #{target} ...?>"
-
end
-
end
-
end
-
1
require 'rexml/xmltokens'
-
-
1
module REXML
-
# Adds named attributes to an object.
-
1
module Namespace
-
# The name of the object, valid if set
-
1
attr_reader :name, :expanded_name
-
# The expanded name of the object, valid if name is set
-
1
attr_accessor :prefix
-
1
include XMLTokens
-
1
NAMESPLIT = /^(?:(#{NCNAME_STR}):)?(#{NCNAME_STR})/u
-
-
# Sets the name and the expanded name
-
1
def name=( name )
-
334
@expanded_name = name
-
334
name =~ NAMESPLIT
-
334
if $1
-
@prefix = $1
-
else
-
334
@prefix = ""
-
334
@namespace = ""
-
end
-
334
@name = $2
-
end
-
-
# Compares names optionally WITH namespaces
-
1
def has_name?( other, ns=nil )
-
if ns
-
return (namespace() == ns and name() == other)
-
elsif other.include? ":"
-
return fully_expanded_name == other
-
else
-
return name == other
-
end
-
end
-
-
1
alias :local_name :name
-
-
# Fully expand the name, even if the prefix wasn't specified in the
-
# source file.
-
1
def fully_expanded_name
-
ns = prefix
-
return "#{ns}:#@name" if ns.size > 0
-
return @name
-
end
-
end
-
end
-
1
require "rexml/parseexception"
-
1
require "rexml/formatters/pretty"
-
1
require "rexml/formatters/default"
-
-
1
module REXML
-
# Represents a node in the tree. Nodes are never encountered except as
-
# superclasses of other objects. Nodes have siblings.
-
1
module Node
-
# @return the next sibling (nil if unset)
-
1
def next_sibling_node
-
return nil if @parent.nil?
-
@parent[ @parent.index(self) + 1 ]
-
end
-
-
# @return the previous sibling (nil if unset)
-
1
def previous_sibling_node
-
return nil if @parent.nil?
-
ind = @parent.index(self)
-
return nil if ind == 0
-
@parent[ ind - 1 ]
-
end
-
-
# indent::
-
# *DEPRECATED* This parameter is now ignored. See the formatters in the
-
# REXML::Formatters package for changing the output style.
-
1
def to_s indent=nil
-
unless indent.nil?
-
Kernel.warn( "#{self.class.name}.to_s(indent) parameter is deprecated" )
-
f = REXML::Formatters::Pretty.new( indent )
-
f.write( self, rv = "" )
-
else
-
f = REXML::Formatters::Default.new
-
f.write( self, rv = "" )
-
end
-
return rv
-
end
-
-
1
def indent to, ind
-
if @parent and @parent.context and not @parent.context[:indentstyle].nil? then
-
indentstyle = @parent.context[:indentstyle]
-
else
-
indentstyle = ' '
-
end
-
to << indentstyle*ind unless ind<1
-
end
-
-
1
def parent?
-
false;
-
end
-
-
-
# Visit all subnodes of +self+ recursively
-
1
def each_recursive(&block) # :yields: node
-
self.elements.each {|node|
-
block.call(node)
-
node.each_recursive(&block)
-
}
-
end
-
-
# Find (and return) first subnode (recursively) for which the block
-
# evaluates to true. Returns +nil+ if none was found.
-
1
def find_first_recursive(&block) # :yields: node
-
each_recursive {|node|
-
return node if block.call(node)
-
}
-
return nil
-
end
-
-
# Returns the position that +self+ holds in its parent's array, indexed
-
# from 1.
-
1
def index_in_parent
-
parent.index(self)+1
-
end
-
end
-
end
-
1
require 'rexml/encoding'
-
-
1
module REXML
-
1
class Output
-
1
include Encoding
-
-
1
attr_reader :encoding
-
-
1
def initialize real_IO, encd="iso-8859-1"
-
@output = real_IO
-
self.encoding = encd
-
-
@to_utf = encd != 'UTF-8'
-
end
-
-
1
def <<( content )
-
@output << (@to_utf ? self.encode(content) : content)
-
end
-
-
1
def to_s
-
"Output[#{encoding}]"
-
end
-
end
-
end
-
1
require "rexml/child"
-
-
1
module REXML
-
# A parent has children, and has methods for accessing them. The Parent
-
# class is never encountered except as the superclass for some other
-
# object.
-
1
class Parent < Child
-
1
include Enumerable
-
-
# Constructor
-
# @param parent if supplied, will be set as the parent of this object
-
1
def initialize parent=nil
-
232
super(parent)
-
232
@children = []
-
end
-
-
1
def add( object )
-
#puts "PARENT GOTS #{size} CHILDREN"
-
572
object.parent = self
-
572
@children << object
-
#puts "PARENT NOW GOTS #{size} CHILDREN"
-
572
object
-
end
-
-
1
alias :push :add
-
1
alias :<< :push
-
-
1
def unshift( object )
-
object.parent = self
-
@children.unshift object
-
end
-
-
1
def delete( object )
-
found = false
-
@children.delete_if {|c| c.equal?(object) and found = true }
-
object.parent = nil if found
-
found ? object : nil
-
end
-
-
1
def each(&block)
-
20735
@children.each(&block)
-
end
-
-
1
def delete_if( &block )
-
@children.delete_if(&block)
-
end
-
-
1
def delete_at( index )
-
@children.delete_at index
-
end
-
-
1
def each_index( &block )
-
@children.each_index(&block)
-
end
-
-
# Fetches a child at a given index
-
# @param index the Integer index of the child to fetch
-
1
def []( index )
-
378
@children[index]
-
end
-
-
1
alias :each_child :each
-
-
-
-
# Set an index entry. See Array.[]=
-
# @param index the index of the element to set
-
# @param opt either the object to set, or an Integer length
-
# @param child if opt is an Integer, this is the child to set
-
# @return the parent (self)
-
1
def []=( *args )
-
args[-1].parent = self
-
@children[*args[0..-2]] = args[-1]
-
end
-
-
# Inserts an child before another child
-
# @param child1 this is either an xpath or an Element. If an Element,
-
# child2 will be inserted before child1 in the child list of the parent.
-
# If an xpath, child2 will be inserted before the first child to match
-
# the xpath.
-
# @param child2 the child to insert
-
# @return the parent (self)
-
1
def insert_before( child1, child2 )
-
if child1.kind_of? String
-
child1 = XPath.first( self, child1 )
-
child1.parent.insert_before child1, child2
-
else
-
ind = index(child1)
-
child2.parent.delete(child2) if child2.parent
-
@children[ind,0] = child2
-
child2.parent = self
-
end
-
self
-
end
-
-
# Inserts an child after another child
-
# @param child1 this is either an xpath or an Element. If an Element,
-
# child2 will be inserted after child1 in the child list of the parent.
-
# If an xpath, child2 will be inserted after the first child to match
-
# the xpath.
-
# @param child2 the child to insert
-
# @return the parent (self)
-
1
def insert_after( child1, child2 )
-
if child1.kind_of? String
-
child1 = XPath.first( self, child1 )
-
child1.parent.insert_after child1, child2
-
else
-
ind = index(child1)+1
-
child2.parent.delete(child2) if child2.parent
-
@children[ind,0] = child2
-
child2.parent = self
-
end
-
self
-
end
-
-
1
def to_a
-
54
@children.dup
-
end
-
-
# Fetches the index of a given child
-
# @param child the child to get the index of
-
# @return the index of the child, or nil if the object is not a child
-
# of this parent.
-
1
def index( child )
-
count = -1
-
@children.find { |i| count += 1 ; i.hash == child.hash }
-
count
-
end
-
-
# @return the number of children of this parent
-
1
def size
-
@children.size
-
end
-
-
1
alias :length :size
-
-
# Replaces one child with another, making sure the nodelist is correct
-
# @param to_replace the child to replace (must be a Child)
-
# @param replacement the child to insert into the nodelist (must be a
-
# Child)
-
1
def replace_child( to_replace, replacement )
-
@children.map! {|c| c.equal?( to_replace ) ? replacement : c }
-
to_replace.parent = nil
-
replacement.parent = self
-
end
-
-
# Deeply clones this object. This creates a complete duplicate of this
-
# Parent, including all descendants.
-
1
def deep_clone
-
cl = clone()
-
each do |child|
-
if child.kind_of? Parent
-
cl << child.deep_clone
-
else
-
cl << child.clone
-
end
-
end
-
cl
-
end
-
-
1
alias :children :to_a
-
-
1
def parent?
-
true
-
end
-
end
-
end
-
1
module REXML
-
1
class ParseException < RuntimeError
-
1
attr_accessor :source, :parser, :continued_exception
-
-
1
def initialize( message, source=nil, parser=nil, exception=nil )
-
super(message)
-
@source = source
-
@parser = parser
-
@continued_exception = exception
-
end
-
-
1
def to_s
-
# Quote the original exception, if there was one
-
if @continued_exception
-
err = @continued_exception.inspect
-
err << "\n"
-
err << @continued_exception.backtrace.join("\n")
-
err << "\n...\n"
-
else
-
err = ""
-
end
-
-
# Get the stack trace and error message
-
err << super
-
-
# Add contextual information
-
if @source
-
err << "\nLine: #{line}\n"
-
err << "Position: #{position}\n"
-
err << "Last 80 unconsumed characters:\n"
-
err << @source.buffer[0..80].force_encoding("ASCII-8BIT").gsub(/\n/, ' ')
-
end
-
-
err
-
end
-
-
1
def position
-
@source.current_line[0] if @source and defined? @source.current_line and
-
@source.current_line
-
end
-
-
1
def line
-
@source.current_line[2] if @source and defined? @source.current_line and
-
@source.current_line
-
end
-
-
1
def context
-
@source.current_line
-
end
-
end
-
end
-
1
require 'rexml/parseexception'
-
1
require 'rexml/undefinednamespaceexception'
-
1
require 'rexml/source'
-
1
require 'set'
-
-
1
module REXML
-
1
module Parsers
-
# = Using the Pull Parser
-
# <em>This API is experimental, and subject to change.</em>
-
# parser = PullParser.new( "<a>text<b att='val'/>txet</a>" )
-
# while parser.has_next?
-
# res = parser.next
-
# puts res[1]['att'] if res.start_tag? and res[0] == 'b'
-
# end
-
# See the PullEvent class for information on the content of the results.
-
# The data is identical to the arguments passed for the various events to
-
# the StreamListener API.
-
#
-
# Notice that:
-
# parser = PullParser.new( "<a>BAD DOCUMENT" )
-
# while parser.has_next?
-
# res = parser.next
-
# raise res[1] if res.error?
-
# end
-
#
-
# Nat Price gave me some good ideas for the API.
-
1
class BaseParser
-
1
LETTER = '[:alpha:]'
-
1
DIGIT = '[:digit:]'
-
-
1
COMBININGCHAR = '' # TODO
-
1
EXTENDER = '' # TODO
-
-
1
NCNAME_STR= "[#{LETTER}_:][-[:alnum:]._:#{COMBININGCHAR}#{EXTENDER}]*"
-
1
NAME_STR= "(?:(#{NCNAME_STR}):)?(#{NCNAME_STR})"
-
1
UNAME_STR= "(?:#{NCNAME_STR}:)?#{NCNAME_STR}"
-
-
1
NAMECHAR = '[\-\w\.:]'
-
1
NAME = "([\\w:]#{NAMECHAR}*)"
-
1
NMTOKEN = "(?:#{NAMECHAR})+"
-
1
NMTOKENS = "#{NMTOKEN}(\\s+#{NMTOKEN})*"
-
1
REFERENCE = "&(?:#{NAME};|#\\d+;|#x[0-9a-fA-F]+;)"
-
1
REFERENCE_RE = /#{REFERENCE}/
-
-
1
DOCTYPE_START = /\A\s*<!DOCTYPE\s/um
-
1
DOCTYPE_PATTERN = /\s*<!DOCTYPE\s+(.*?)(\[|>)/um
-
1
ATTRIBUTE_PATTERN = /\s*(#{NAME_STR})\s*=\s*(["'])(.*?)\4/um
-
1
COMMENT_START = /\A<!--/u
-
1
COMMENT_PATTERN = /<!--(.*?)-->/um
-
1
CDATA_START = /\A<!\[CDATA\[/u
-
1
CDATA_END = /^\s*\]\s*>/um
-
1
CDATA_PATTERN = /<!\[CDATA\[(.*?)\]\]>/um
-
1
XMLDECL_START = /\A<\?xml\s/u;
-
1
XMLDECL_PATTERN = /<\?xml\s+(.*?)\?>/um
-
1
INSTRUCTION_START = /\A<\?/u
-
1
INSTRUCTION_PATTERN = /<\?(.*?)(\s+.*?)?\?>/um
-
1
TAG_MATCH = /^<((?>#{NAME_STR}))\s*((?>\s+#{UNAME_STR}\s*=\s*(["']).*?\5)*)\s*(\/)?>/um
-
1
CLOSE_MATCH = /^\s*<\/(#{NAME_STR})\s*>/um
-
-
1
VERSION = /\bversion\s*=\s*["'](.*?)['"]/um
-
1
ENCODING = /\bencoding\s*=\s*["'](.*?)['"]/um
-
1
STANDALONE = /\bstandalone\s*=\s*["'](.*?)['"]/um
-
-
1
ENTITY_START = /^\s*<!ENTITY/
-
1
IDENTITY = /^([!\*\w\-]+)(\s+#{NCNAME_STR})?(\s+["'](.*?)['"])?(\s+['"](.*?)["'])?/u
-
1
ELEMENTDECL_START = /^\s*<!ELEMENT/um
-
1
ELEMENTDECL_PATTERN = /^\s*(<!ELEMENT.*?)>/um
-
1
SYSTEMENTITY = /^\s*(%.*?;)\s*$/um
-
1
ENUMERATION = "\\(\\s*#{NMTOKEN}(?:\\s*\\|\\s*#{NMTOKEN})*\\s*\\)"
-
1
NOTATIONTYPE = "NOTATION\\s+\\(\\s*#{NAME}(?:\\s*\\|\\s*#{NAME})*\\s*\\)"
-
1
ENUMERATEDTYPE = "(?:(?:#{NOTATIONTYPE})|(?:#{ENUMERATION}))"
-
1
ATTTYPE = "(CDATA|ID|IDREF|IDREFS|ENTITY|ENTITIES|NMTOKEN|NMTOKENS|#{ENUMERATEDTYPE})"
-
1
ATTVALUE = "(?:\"((?:[^<&\"]|#{REFERENCE})*)\")|(?:'((?:[^<&']|#{REFERENCE})*)')"
-
1
DEFAULTDECL = "(#REQUIRED|#IMPLIED|(?:(#FIXED\\s+)?#{ATTVALUE}))"
-
1
ATTDEF = "\\s+#{NAME}\\s+#{ATTTYPE}\\s+#{DEFAULTDECL}"
-
1
ATTDEF_RE = /#{ATTDEF}/
-
1
ATTLISTDECL_START = /^\s*<!ATTLIST/um
-
1
ATTLISTDECL_PATTERN = /^\s*<!ATTLIST\s+#{NAME}(?:#{ATTDEF})*\s*>/um
-
1
NOTATIONDECL_START = /^\s*<!NOTATION/um
-
1
PUBLIC = /^\s*<!NOTATION\s+(\w[\-\w]*)\s+(PUBLIC)\s+(["'])(.*?)\3(?:\s+(["'])(.*?)\5)?\s*>/um
-
1
SYSTEM = /^\s*<!NOTATION\s+(\w[\-\w]*)\s+(SYSTEM)\s+(["'])(.*?)\3\s*>/um
-
-
1
TEXT_PATTERN = /\A([^<]*)/um
-
-
# Entity constants
-
1
PUBIDCHAR = "\x20\x0D\x0Aa-zA-Z0-9\\-()+,./:=?;!*@$_%#"
-
1
SYSTEMLITERAL = %Q{((?:"[^"]*")|(?:'[^']*'))}
-
1
PUBIDLITERAL = %Q{("[#{PUBIDCHAR}']*"|'[#{PUBIDCHAR}]*')}
-
1
EXTERNALID = "(?:(?:(SYSTEM)\\s+#{SYSTEMLITERAL})|(?:(PUBLIC)\\s+#{PUBIDLITERAL}\\s+#{SYSTEMLITERAL}))"
-
1
NDATADECL = "\\s+NDATA\\s+#{NAME}"
-
1
PEREFERENCE = "%#{NAME};"
-
1
ENTITYVALUE = %Q{((?:"(?:[^%&"]|#{PEREFERENCE}|#{REFERENCE})*")|(?:'([^%&']|#{PEREFERENCE}|#{REFERENCE})*'))}
-
1
PEDEF = "(?:#{ENTITYVALUE}|#{EXTERNALID})"
-
1
ENTITYDEF = "(?:#{ENTITYVALUE}|(?:#{EXTERNALID}(#{NDATADECL})?))"
-
1
PEDECL = "<!ENTITY\\s+(%)\\s+#{NAME}\\s+#{PEDEF}\\s*>"
-
1
GEDECL = "<!ENTITY\\s+#{NAME}\\s+#{ENTITYDEF}\\s*>"
-
1
ENTITYDECL = /\s*(?:#{GEDECL})|(?:#{PEDECL})/um
-
-
1
EREFERENCE = /&(?!#{NAME};)/
-
-
1
DEFAULT_ENTITIES = {
-
'gt' => [/>/, '>', '>', />/],
-
'lt' => [/</, '<', '<', /</],
-
'quot' => [/"/, '"', '"', /"/],
-
"apos" => [/'/, "'", "'", /'/]
-
}
-
-
-
######################################################################
-
# These are patterns to identify common markup errors, to make the
-
# error messages more informative.
-
######################################################################
-
1
MISSING_ATTRIBUTE_QUOTES = /^<#{NAME_STR}\s+#{NAME_STR}\s*=\s*[^"']/um
-
-
1
def initialize( source )
-
51
self.stream = source
-
end
-
-
1
def add_listener( listener )
-
if !defined?(@listeners) or !@listeners
-
@listeners = []
-
instance_eval <<-EOL
-
alias :_old_pull :pull
-
def pull
-
event = _old_pull
-
@listeners.each do |listener|
-
listener.receive event
-
end
-
event
-
end
-
EOL
-
end
-
@listeners << listener
-
end
-
-
1
attr_reader :source
-
-
1
def stream=( source )
-
51
@source = SourceFactory.create_from( source )
-
51
@closed = nil
-
51
@document_status = nil
-
51
@tags = []
-
51
@stack = []
-
51
@entities = []
-
51
@nsstack = []
-
end
-
-
1
def position
-
if @source.respond_to? :position
-
@source.position
-
else
-
# FIXME
-
0
-
end
-
end
-
-
# Returns true if there are no more events
-
1
def empty?
-
794
return (@source.empty? and @stack.empty?)
-
end
-
-
# Returns true if there are more events. Synonymous with !empty?
-
1
def has_next?
-
return !(@source.empty? and @stack.empty?)
-
end
-
-
# Push an event back on the head of the stream. This method
-
# has (theoretically) infinite depth.
-
1
def unshift token
-
@stack.unshift(token)
-
end
-
-
# Peek at the +depth+ event in the stack. The first element on the stack
-
# is at depth 0. If +depth+ is -1, will parse to the end of the input
-
# stream and return the last event, which is always :end_document.
-
# Be aware that this causes the stream to be parsed up to the +depth+
-
# event, so you can effectively pre-parse the entire document (pull the
-
# entire thing into memory) using this method.
-
1
def peek depth=0
-
raise %Q[Illegal argument "#{depth}"] if depth < -1
-
temp = []
-
if depth == -1
-
temp.push(pull()) until empty?
-
else
-
while @stack.size+temp.size < depth+1
-
temp.push(pull())
-
end
-
end
-
@stack += temp if temp.size > 0
-
@stack[depth]
-
end
-
-
# Returns the next event. This is a +PullEvent+ object.
-
1
def pull
-
807
if @closed
-
13
x, @closed = @closed, nil
-
13
return [ :end_element, x ]
-
end
-
794
return [ :end_document ] if empty?
-
743
return @stack.shift if @stack.size > 0
-
#STDERR.puts @source.encoding
-
743
@source.read if @source.buffer.size<2
-
#STDERR.puts "BUFFER = #{@source.buffer.inspect}"
-
743
if @document_status == nil
-
#@source.consume( /^\s*/um )
-
101
word = @source.match( /^((?:\s+)|(?:<[^>]*>))/um )
-
101
word = word[1] unless word.nil?
-
#STDERR.puts "WORD = #{word.inspect}"
-
101
case word
-
when COMMENT_START
-
return [ :comment, @source.match( COMMENT_PATTERN, true )[1] ]
-
when XMLDECL_START
-
#STDERR.puts "XMLDECL"
-
1
results = @source.match( XMLDECL_PATTERN, true )[1]
-
1
version = VERSION.match( results )
-
1
version = version[1] unless version.nil?
-
1
encoding = ENCODING.match(results)
-
1
encoding = encoding[1] unless encoding.nil?
-
1
@source.encoding = encoding
-
1
standalone = STANDALONE.match(results)
-
1
standalone = standalone[1] unless standalone.nil?
-
1
return [ :xmldecl, version, encoding, standalone ]
-
when INSTRUCTION_START
-
return [ :processing_instruction, *@source.match(INSTRUCTION_PATTERN, true)[1,2] ]
-
when DOCTYPE_START
-
1
md = @source.match( DOCTYPE_PATTERN, true )
-
1
@nsstack.unshift(curr_ns=Set.new)
-
1
identity = md[1]
-
1
close = md[2]
-
1
identity =~ IDENTITY
-
1
name = $1
-
1
raise REXML::ParseException.new("DOCTYPE is missing a name") if name.nil?
-
1
pub_sys = $2.nil? ? nil : $2.strip
-
1
long_name = $4.nil? ? nil : $4.strip
-
1
uri = $6.nil? ? nil : $6.strip
-
1
args = [ :start_doctype, name, pub_sys, long_name, uri ]
-
1
if close == ">"
-
@document_status = :after_doctype
-
@source.read if @source.buffer.size<2
-
md = @source.match(/^\s*/um, true)
-
@stack << [ :end_doctype ]
-
else
-
1
@document_status = :in_doctype
-
end
-
1
return args
-
when /^\s+/
-
else
-
50
@document_status = :after_doctype
-
50
@source.read if @source.buffer.size<2
-
50
md = @source.match(/\s*/um, true)
-
50
if @source.encoding == "UTF-8"
-
50
@source.buffer.force_encoding(::Encoding::UTF_8)
-
end
-
end
-
end
-
741
if @document_status == :in_doctype
-
8
md = @source.match(/\s*(.*?>)/um)
-
8
case md[1]
-
when SYSTEMENTITY
-
match = @source.match( SYSTEMENTITY, true )[1]
-
return [ :externalentity, match ]
-
-
when ELEMENTDECL_START
-
return [ :elementdecl, @source.match( ELEMENTDECL_PATTERN, true )[1] ]
-
-
when ENTITY_START
-
7
match = @source.match( ENTITYDECL, true ).to_a.compact
-
7
match[0] = :entitydecl
-
7
ref = false
-
7
if match[1] == '%'
-
ref = true
-
match.delete_at 1
-
end
-
# Now we have to sort out what kind of entity reference this is
-
7
if match[2] == 'SYSTEM'
-
# External reference
-
match[3] = match[3][1..-2] # PUBID
-
match.delete_at(4) if match.size > 4 # Chop out NDATA decl
-
# match is [ :entity, name, SYSTEM, pubid(, ndata)? ]
-
elsif match[2] == 'PUBLIC'
-
# External reference
-
match[3] = match[3][1..-2] # PUBID
-
match[4] = match[4][1..-2] # HREF
-
# match is [ :entity, name, PUBLIC, pubid, href ]
-
else
-
7
match[2] = match[2][1..-2]
-
7
match.pop if match.size == 4
-
# match is [ :entity, name, value ]
-
end
-
7
match << '%' if ref
-
7
return match
-
when ATTLISTDECL_START
-
md = @source.match( ATTLISTDECL_PATTERN, true )
-
raise REXML::ParseException.new( "Bad ATTLIST declaration!", @source ) if md.nil?
-
element = md[1]
-
contents = md[0]
-
-
pairs = {}
-
values = md[0].scan( ATTDEF_RE )
-
values.each do |attdef|
-
unless attdef[3] == "#IMPLIED"
-
attdef.compact!
-
val = attdef[3]
-
val = attdef[4] if val == "#FIXED "
-
pairs[attdef[0]] = val
-
if attdef[0] =~ /^xmlns:(.*)/
-
@nsstack[0] << $1
-
end
-
end
-
end
-
return [ :attlistdecl, element, pairs, contents ]
-
when NOTATIONDECL_START
-
md = nil
-
if @source.match( PUBLIC )
-
md = @source.match( PUBLIC, true )
-
vals = [md[1],md[2],md[4],md[6]]
-
elsif @source.match( SYSTEM )
-
md = @source.match( SYSTEM, true )
-
vals = [md[1],md[2],nil,md[4]]
-
else
-
raise REXML::ParseException.new( "error parsing notation: no matching pattern", @source )
-
end
-
return [ :notationdecl, *vals ]
-
when CDATA_END
-
1
@document_status = :after_doctype
-
1
@source.match( CDATA_END, true )
-
1
return [ :end_doctype ]
-
end
-
end
-
733
begin
-
733
if @source.buffer[0] == ?<
-
356
if @source.buffer[1] == ?/
-
167
@nsstack.shift
-
167
last_tag = @tags.pop
-
#md = @source.match_to_consume( '>', CLOSE_MATCH)
-
167
md = @source.match( CLOSE_MATCH, true )
-
raise REXML::ParseException.new( "Missing end tag for "+
-
"'#{last_tag}' (got \"#{md[1]}\")",
-
167
@source) unless last_tag == md[1]
-
167
return [ :end_element, last_tag ]
-
elsif @source.buffer[1] == ?!
-
9
md = @source.match(/\A(\s*[^>]*>)/um)
-
#STDERR.puts "SOURCE BUFFER = #{source.buffer}, #{source.buffer.size}"
-
9
raise REXML::ParseException.new("Malformed node", @source) unless md
-
9
if md[0][2] == ?-
-
md = @source.match( COMMENT_PATTERN, true )
-
-
case md[1]
-
when /--/, /-$/
-
raise REXML::ParseException.new("Malformed comment", @source)
-
end
-
-
return [ :comment, md[1] ] if md
-
else
-
9
md = @source.match( CDATA_PATTERN, true )
-
9
return [ :cdata, md[1] ] if md
-
end
-
raise REXML::ParseException.new( "Declarations can only occur "+
-
"in the doctype declaration.", @source)
-
elsif @source.buffer[1] == ??
-
md = @source.match( INSTRUCTION_PATTERN, true )
-
return [ :processing_instruction, md[1], md[2] ] if md
-
raise REXML::ParseException.new( "Bad instruction declaration",
-
@source)
-
else
-
# Get the next tag
-
180
md = @source.match(TAG_MATCH, true)
-
180
unless md
-
# Check for missing attribute quotes
-
raise REXML::ParseException.new("missing attribute quote", @source) if @source.match(MISSING_ATTRIBUTE_QUOTES )
-
raise REXML::ParseException.new("malformed XML: missing tag start", @source)
-
end
-
180
attributes = {}
-
180
prefixes = Set.new
-
180
prefixes << md[2] if md[2]
-
180
@nsstack.unshift(curr_ns=Set.new)
-
180
if md[4].size > 0
-
79
attrs = md[4].scan( ATTRIBUTE_PATTERN )
-
79
raise REXML::ParseException.new( "error parsing attributes: [#{attrs.join ', '}], excess = \"#$'\"", @source) if $' and $'.strip.size > 0
-
79
attrs.each { |a,b,c,d,e|
-
103
if b == "xmlns"
-
if c == "xml"
-
if d != "http://www.w3.org/XML/1998/namespace"
-
msg = "The 'xml' prefix must not be bound to any other namespace "+
-
"(http://www.w3.org/TR/REC-xml-names/#ns-decl)"
-
raise REXML::ParseException.new( msg, @source, self )
-
end
-
elsif c == "xmlns"
-
msg = "The 'xmlns' prefix must not be declared "+
-
"(http://www.w3.org/TR/REC-xml-names/#ns-decl)"
-
raise REXML::ParseException.new( msg, @source, self)
-
end
-
curr_ns << c
-
elsif b
-
prefixes << b unless b == "xml"
-
end
-
-
103
if attributes.has_key? a
-
msg = "Duplicate attribute #{a.inspect}"
-
raise REXML::ParseException.new( msg, @source, self)
-
end
-
-
103
attributes[a] = e
-
}
-
end
-
-
# Verify that all of the prefixes have been defined
-
180
for prefix in prefixes
-
unless @nsstack.find{|k| k.member?(prefix)}
-
raise UndefinedNamespaceException.new(prefix,@source,self)
-
end
-
end
-
-
180
if md[6]
-
13
@closed = md[1]
-
13
@nsstack.shift
-
else
-
167
@tags.push( md[1] )
-
end
-
180
return [ :start_element, md[1], attributes ]
-
end
-
else
-
377
md = @source.match( TEXT_PATTERN, true )
-
377
if md[0].length == 0
-
@source.match( /(\s+)/, true )
-
end
-
#STDERR.puts "GOT #{md[1].inspect}" unless md[0].length == 0
-
#return [ :text, "" ] if md[0].length == 0
-
# unnormalized = Text::unnormalize( md[1], self )
-
# return PullEvent.new( :text, md[1], unnormalized )
-
377
return [ :text, md[1] ]
-
end
-
rescue REXML::UndefinedNamespaceException
-
raise
-
rescue REXML::ParseException
-
raise
-
rescue Exception, NameError => error
-
raise REXML::ParseException.new( "Exception parsing",
-
@source, self, (error ? error : $!) )
-
end
-
return [ :dummy ]
-
end
-
-
1
def entity( reference, entities )
-
value = nil
-
value = entities[ reference ] if entities
-
if not value
-
value = DEFAULT_ENTITIES[ reference ]
-
value = value[2] if value
-
end
-
unnormalize( value, entities ) if value
-
end
-
-
# Escapes all possible entities
-
1
def normalize( input, entities=nil, entity_filter=nil )
-
copy = input.clone
-
# Doing it like this rather than in a loop improves the speed
-
copy.gsub!( EREFERENCE, '&' )
-
entities.each do |key, value|
-
copy.gsub!( value, "&#{key};" ) unless entity_filter and
-
entity_filter.include?(entity)
-
end if entities
-
copy.gsub!( EREFERENCE, '&' )
-
DEFAULT_ENTITIES.each do |key, value|
-
copy.gsub!( value[3], value[1] )
-
end
-
copy
-
end
-
-
# Unescapes all possible entities
-
1
def unnormalize( string, entities=nil, filter=nil )
-
rv = string.clone
-
rv.gsub!( /\r\n?/, "\n" )
-
matches = rv.scan( REFERENCE_RE )
-
return rv if matches.size == 0
-
rv.gsub!( /�*((?:\d+)|(?:x[a-fA-F0-9]+));/ ) {
-
m=$1
-
m = "0#{m}" if m[0] == ?x
-
[Integer(m)].pack('U*')
-
}
-
matches.collect!{|x|x[0]}.compact!
-
if matches.size > 0
-
matches.each do |entity_reference|
-
unless filter and filter.include?(entity_reference)
-
entity_value = entity( entity_reference, entities )
-
if entity_value
-
re = /&#{entity_reference};/
-
rv.gsub!( re, entity_value )
-
else
-
er = DEFAULT_ENTITIES[entity_reference]
-
rv.gsub!( er[0], er[2] ) if er
-
end
-
end
-
end
-
rv.gsub!( /&/, '&' )
-
end
-
rv
-
end
-
end
-
end
-
end
-
-
=begin
-
case event[0]
-
when :start_element
-
when :text
-
when :end_element
-
when :processing_instruction
-
when :cdata
-
when :comment
-
when :xmldecl
-
when :start_doctype
-
when :end_doctype
-
when :externalentity
-
when :elementdecl
-
when :entity
-
when :attlistdecl
-
when :notationdecl
-
when :end_doctype
-
end
-
=end
-
1
module REXML
-
1
module Parsers
-
1
class StreamParser
-
1
def initialize source, listener
-
@listener = listener
-
@parser = BaseParser.new( source )
-
end
-
-
1
def add_listener( listener )
-
@parser.add_listener( listener )
-
end
-
-
1
def parse
-
# entity string
-
while true
-
event = @parser.pull
-
case event[0]
-
when :end_document
-
return
-
when :start_element
-
attrs = event[2].each do |n, v|
-
event[2][n] = @parser.unnormalize( v )
-
end
-
@listener.tag_start( event[1], attrs )
-
when :end_element
-
@listener.tag_end( event[1] )
-
when :text
-
normalized = @parser.unnormalize( event[1] )
-
@listener.text( normalized )
-
when :processing_instruction
-
@listener.instruction( *event[1,2] )
-
when :start_doctype
-
@listener.doctype( *event[1..-1] )
-
when :end_doctype
-
# FIXME: remove this condition for milestone:3.2
-
@listener.doctype_end if @listener.respond_to? :doctype_end
-
when :comment, :attlistdecl, :cdata, :xmldecl, :elementdecl
-
@listener.send( event[0].to_s, *event[1..-1] )
-
when :entitydecl, :notationdecl
-
@listener.send( event[0].to_s, event[1..-1] )
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'rexml/validation/validationexception'
-
1
require 'rexml/undefinednamespaceexception'
-
-
1
module REXML
-
1
module Parsers
-
1
class TreeParser
-
1
def initialize( source, build_context = Document.new )
-
51
@build_context = build_context
-
51
@parser = Parsers::BaseParser.new( source )
-
end
-
-
1
def add_listener( listener )
-
@parser.add_listener( listener )
-
end
-
-
1
def parse
-
51
tag_stack = []
-
51
in_doctype = false
-
51
entities = nil
-
51
begin
-
51
while true
-
807
event = @parser.pull
-
#STDERR.puts "TREEPARSER GOT #{event.inspect}"
-
807
case event[0]
-
when :end_document
-
51
unless tag_stack.empty?
-
#raise ParseException.new("No close tag for #{tag_stack.inspect}")
-
raise ParseException.new("No close tag for #{@build_context.xpath}")
-
end
-
51
return
-
when :start_element
-
180
tag_stack.push(event[1])
-
180
el = @build_context = @build_context.add_element( event[1] )
-
180
event[2].each do |key, value|
-
103
el.attributes[key]=Attribute.new(key,value,self)
-
end
-
when :end_element
-
180
tag_stack.pop
-
180
@build_context = @build_context.parent
-
when :text
-
377
if not in_doctype
-
377
if @build_context[-1].instance_of? Text
-
1
@build_context[-1] << event[1]
-
else
-
@build_context.add(
-
Text.new(event[1], @build_context.whitespace, nil, true)
-
) unless (
-
@build_context.ignore_whitespace_nodes and
-
376
event[1].strip.size==0
-
)
-
end
-
end
-
when :comment
-
c = Comment.new( event[1] )
-
@build_context.add( c )
-
when :cdata
-
9
c = CData.new( event[1] )
-
9
@build_context.add( c )
-
when :processing_instruction
-
@build_context.add( Instruction.new( event[1], event[2] ) )
-
when :end_doctype
-
1
in_doctype = false
-
8
entities.each { |k,v| entities[k] = @build_context.entities[k].value }
-
1
@build_context = @build_context.parent
-
when :start_doctype
-
1
doctype = DocType.new( event[1..-1], @build_context )
-
1
@build_context = doctype
-
1
entities = {}
-
1
in_doctype = true
-
when :attlistdecl
-
n = AttlistDecl.new( event[1..-1] )
-
@build_context.add( n )
-
when :externalentity
-
n = ExternalEntity.new( event[1] )
-
@build_context.add( n )
-
when :elementdecl
-
n = ElementDecl.new( event[1] )
-
@build_context.add(n)
-
when :entitydecl
-
7
entities[ event[1] ] = event[2] unless event[2] =~ /PUBLIC|SYSTEM/
-
7
@build_context.add(Entity.new(event))
-
when :notationdecl
-
n = NotationDecl.new( *event[1..-1] )
-
@build_context.add( n )
-
when :xmldecl
-
1
x = XMLDecl.new( event[1], event[2], event[3] )
-
1
@build_context.add( x )
-
end
-
end
-
rescue REXML::Validation::ValidationException
-
raise
-
rescue REXML::UndefinedNamespaceException
-
raise
-
rescue
-
raise ParseException.new( $!.message, @parser.source, @parser, $! )
-
end
-
end
-
end
-
end
-
end
-
1
require 'rexml/namespace'
-
1
require 'rexml/xmltokens'
-
-
1
module REXML
-
1
module Parsers
-
# You don't want to use this class. Really. Use XPath, which is a wrapper
-
# for this class. Believe me. You don't want to poke around in here.
-
# There is strange, dark magic at work in this code. Beware. Go back! Go
-
# back while you still can!
-
1
class XPathParser
-
1
include XMLTokens
-
1
LITERAL = /^'([^']*)'|^"([^"]*)"/u
-
-
1
def namespaces=( namespaces )
-
Functions::namespace_context = namespaces
-
@namespaces = namespaces
-
end
-
-
1
def parse path
-
54
path = path.dup
-
54
path.gsub!(/([\(\[])\s+/, '\1') # Strip ignorable spaces
-
54
path.gsub!( /\s+([\]\)])/, '\1')
-
54
parsed = []
-
54
path = OrExpr(path, parsed)
-
54
parsed
-
end
-
-
1
def predicate path
-
parsed = []
-
Predicate( "[#{path}]", parsed )
-
parsed
-
end
-
-
1
def abbreviate( path )
-
path = path.kind_of?(String) ? parse( path ) : path
-
string = ""
-
document = false
-
while path.size > 0
-
op = path.shift
-
case op
-
when :node
-
when :attribute
-
string << "/" if string.size > 0
-
string << "@"
-
when :child
-
string << "/" if string.size > 0
-
when :descendant_or_self
-
string << "/"
-
when :self
-
string << "."
-
when :parent
-
string << ".."
-
when :any
-
string << "*"
-
when :text
-
string << "text()"
-
when :following, :following_sibling,
-
:ancestor, :ancestor_or_self, :descendant,
-
:namespace, :preceding, :preceding_sibling
-
string << "/" unless string.size == 0
-
string << op.to_s.tr("_", "-")
-
string << "::"
-
when :qname
-
prefix = path.shift
-
name = path.shift
-
string << prefix+":" if prefix.size > 0
-
string << name
-
when :predicate
-
string << '['
-
string << predicate_to_string( path.shift ) {|x| abbreviate( x ) }
-
string << ']'
-
when :document
-
document = true
-
when :function
-
string << path.shift
-
string << "( "
-
string << predicate_to_string( path.shift[0] ) {|x| abbreviate( x )}
-
string << " )"
-
when :literal
-
string << %Q{ "#{path.shift}" }
-
else
-
string << "/" unless string.size == 0
-
string << "UNKNOWN("
-
string << op.inspect
-
string << ")"
-
end
-
end
-
string = "/"+string if document
-
return string
-
end
-
-
1
def expand( path )
-
path = path.kind_of?(String) ? parse( path ) : path
-
string = ""
-
document = false
-
while path.size > 0
-
op = path.shift
-
case op
-
when :node
-
string << "node()"
-
when :attribute, :child, :following, :following_sibling,
-
:ancestor, :ancestor_or_self, :descendant, :descendant_or_self,
-
:namespace, :preceding, :preceding_sibling, :self, :parent
-
string << "/" unless string.size == 0
-
string << op.to_s.tr("_", "-")
-
string << "::"
-
when :any
-
string << "*"
-
when :qname
-
prefix = path.shift
-
name = path.shift
-
string << prefix+":" if prefix.size > 0
-
string << name
-
when :predicate
-
string << '['
-
string << predicate_to_string( path.shift ) { |x| expand(x) }
-
string << ']'
-
when :document
-
document = true
-
else
-
string << "/" unless string.size == 0
-
string << "UNKNOWN("
-
string << op.inspect
-
string << ")"
-
end
-
end
-
string = "/"+string if document
-
return string
-
end
-
-
1
def predicate_to_string( path, &block )
-
string = ""
-
case path[0]
-
when :and, :or, :mult, :plus, :minus, :neq, :eq, :lt, :gt, :lteq, :gteq, :div, :mod, :union
-
op = path.shift
-
case op
-
when :eq
-
op = "="
-
when :lt
-
op = "<"
-
when :gt
-
op = ">"
-
when :lteq
-
op = "<="
-
when :gteq
-
op = ">="
-
when :neq
-
op = "!="
-
when :union
-
op = "|"
-
end
-
left = predicate_to_string( path.shift, &block )
-
right = predicate_to_string( path.shift, &block )
-
string << " "
-
string << left
-
string << " "
-
string << op.to_s
-
string << " "
-
string << right
-
string << " "
-
when :function
-
path.shift
-
name = path.shift
-
string << name
-
string << "( "
-
string << predicate_to_string( path.shift, &block )
-
string << " )"
-
when :literal
-
path.shift
-
string << " "
-
string << path.shift.inspect
-
string << " "
-
else
-
string << " "
-
string << yield( path )
-
string << " "
-
end
-
return string.squeeze(" ")
-
end
-
-
1
private
-
#LocationPath
-
# | RelativeLocationPath
-
# | '/' RelativeLocationPath?
-
# | '//' RelativeLocationPath
-
1
def LocationPath path, parsed
-
#puts "LocationPath '#{path}'"
-
54
path = path.strip
-
54
if path[0] == ?/
-
parsed << :document
-
if path[1] == ?/
-
parsed << :descendant_or_self
-
parsed << :node
-
path = path[2..-1]
-
else
-
path = path[1..-1]
-
end
-
end
-
#puts parsed.inspect
-
54
return RelativeLocationPath( path, parsed ) if path.size > 0
-
end
-
-
#RelativeLocationPath
-
# | Step
-
# | (AXIS_NAME '::' | '@' | '') AxisSpecifier
-
# NodeTest
-
# Predicate
-
# | '.' | '..' AbbreviatedStep
-
# | RelativeLocationPath '/' Step
-
# | RelativeLocationPath '//' Step
-
1
AXIS = /^(ancestor|ancestor-or-self|attribute|child|descendant|descendant-or-self|following|following-sibling|namespace|parent|preceding|preceding-sibling|self)::/
-
1
def RelativeLocationPath path, parsed
-
#puts "RelativeLocationPath #{path}"
-
54
while path.size > 0
-
# (axis or @ or <child::>) nodetest predicate >
-
# OR > / Step
-
# (. or ..) >
-
54
if path[0] == ?.
-
if path[1] == ?.
-
parsed << :parent
-
parsed << :node
-
path = path[2..-1]
-
else
-
parsed << :self
-
parsed << :node
-
path = path[1..-1]
-
end
-
else
-
54
if path[0] == ?@
-
#puts "ATTRIBUTE"
-
parsed << :attribute
-
path = path[1..-1]
-
# Goto Nodetest
-
elsif path =~ AXIS
-
parsed << $1.tr('-','_').intern
-
path = $'
-
# Goto Nodetest
-
else
-
54
parsed << :child
-
end
-
-
#puts "NODETESTING '#{path}'"
-
54
n = []
-
54
path = NodeTest( path, n)
-
#puts "NODETEST RETURNED '#{path}'"
-
-
54
if path[0] == ?[
-
path = Predicate( path, n )
-
end
-
-
54
parsed.concat(n)
-
end
-
-
54
if path.size > 0
-
if path[0] == ?/
-
if path[1] == ?/
-
parsed << :descendant_or_self
-
parsed << :node
-
path = path[2..-1]
-
else
-
path = path[1..-1]
-
end
-
else
-
return path
-
end
-
end
-
end
-
54
return path
-
end
-
-
# Returns a 1-1 map of the nodeset
-
# The contents of the resulting array are either:
-
# true/false, if a positive match
-
# String, if a name match
-
#NodeTest
-
# | ('*' | NCNAME ':' '*' | QNAME) NameTest
-
# | NODE_TYPE '(' ')' NodeType
-
# | PI '(' LITERAL ')' PI
-
# | '[' expr ']' Predicate
-
1
NCNAMETEST= /^(#{NCNAME_STR}):\*/u
-
1
QNAME = Namespace::NAMESPLIT
-
1
NODE_TYPE = /^(comment|text|node)\(\s*\)/m
-
1
PI = /^processing-instruction\(/
-
1
def NodeTest path, parsed
-
#puts "NodeTest with #{path}"
-
54
case path
-
when /^\*/
-
54
path = $'
-
54
parsed << :any
-
when NODE_TYPE
-
type = $1
-
path = $'
-
parsed << type.tr('-', '_').intern
-
when PI
-
path = $'
-
literal = nil
-
if path !~ /^\s*\)/
-
path =~ LITERAL
-
literal = $1
-
path = $'
-
raise ParseException.new("Missing ')' after processing instruction") if path[0] != ?)
-
path = path[1..-1]
-
end
-
parsed << :processing_instruction
-
parsed << (literal || '')
-
when NCNAMETEST
-
#puts "NCNAMETEST"
-
prefix = $1
-
path = $'
-
parsed << :namespace
-
parsed << prefix
-
when QNAME
-
#puts "QNAME"
-
prefix = $1
-
name = $2
-
path = $'
-
prefix = "" unless prefix
-
parsed << :qname
-
parsed << prefix
-
parsed << name
-
end
-
54
return path
-
end
-
-
# Filters the supplied nodeset on the predicate(s)
-
1
def Predicate path, parsed
-
#puts "PREDICATE with #{path}"
-
return nil unless path[0] == ?[
-
predicates = []
-
while path[0] == ?[
-
path, expr = get_group(path)
-
predicates << expr[1..-2] if expr
-
end
-
#puts "PREDICATES = #{predicates.inspect}"
-
predicates.each{ |pred|
-
#puts "ORING #{pred}"
-
preds = []
-
parsed << :predicate
-
parsed << preds
-
OrExpr(pred, preds)
-
}
-
#puts "PREDICATES = #{predicates.inspect}"
-
path
-
end
-
-
# The following return arrays of true/false, a 1-1 mapping of the
-
# supplied nodeset, except for axe(), which returns a filtered
-
# nodeset
-
-
#| OrExpr S 'or' S AndExpr
-
#| AndExpr
-
1
def OrExpr path, parsed
-
#puts "OR >>> #{path}"
-
54
n = []
-
54
rest = AndExpr( path, n )
-
#puts "OR <<< #{rest}"
-
54
if rest != path
-
54
while rest =~ /^\s*( or )/
-
n = [ :or, n, [] ]
-
rest = AndExpr( $', n[-1] )
-
end
-
end
-
54
if parsed.size == 0 and n.size != 0
-
54
parsed.replace(n)
-
elsif n.size > 0
-
parsed << n
-
end
-
54
rest
-
end
-
-
#| AndExpr S 'and' S EqualityExpr
-
#| EqualityExpr
-
1
def AndExpr path, parsed
-
#puts "AND >>> #{path}"
-
54
n = []
-
54
rest = EqualityExpr( path, n )
-
#puts "AND <<< #{rest}"
-
54
if rest != path
-
54
while rest =~ /^\s*( and )/
-
n = [ :and, n, [] ]
-
#puts "AND >>> #{rest}"
-
rest = EqualityExpr( $', n[-1] )
-
#puts "AND <<< #{rest}"
-
end
-
end
-
54
if parsed.size == 0 and n.size != 0
-
54
parsed.replace(n)
-
elsif n.size > 0
-
parsed << n
-
end
-
54
rest
-
end
-
-
#| EqualityExpr ('=' | '!=') RelationalExpr
-
#| RelationalExpr
-
1
def EqualityExpr path, parsed
-
#puts "EQUALITY >>> #{path}"
-
54
n = []
-
54
rest = RelationalExpr( path, n )
-
#puts "EQUALITY <<< #{rest}"
-
54
if rest != path
-
54
while rest =~ /^\s*(!?=)\s*/
-
if $1[0] == ?!
-
n = [ :neq, n, [] ]
-
else
-
n = [ :eq, n, [] ]
-
end
-
rest = RelationalExpr( $', n[-1] )
-
end
-
end
-
54
if parsed.size == 0 and n.size != 0
-
54
parsed.replace(n)
-
elsif n.size > 0
-
parsed << n
-
end
-
54
rest
-
end
-
-
#| RelationalExpr ('<' | '>' | '<=' | '>=') AdditiveExpr
-
#| AdditiveExpr
-
1
def RelationalExpr path, parsed
-
#puts "RELATION >>> #{path}"
-
54
n = []
-
54
rest = AdditiveExpr( path, n )
-
#puts "RELATION <<< #{rest}"
-
54
if rest != path
-
54
while rest =~ /^\s*([<>]=?)\s*/
-
if $1[0] == ?<
-
sym = "lt"
-
else
-
sym = "gt"
-
end
-
sym << "eq" if $1[-1] == ?=
-
n = [ sym.intern, n, [] ]
-
rest = AdditiveExpr( $', n[-1] )
-
end
-
end
-
54
if parsed.size == 0 and n.size != 0
-
54
parsed.replace(n)
-
elsif n.size > 0
-
parsed << n
-
end
-
54
rest
-
end
-
-
#| AdditiveExpr ('+' | S '-') MultiplicativeExpr
-
#| MultiplicativeExpr
-
1
def AdditiveExpr path, parsed
-
#puts "ADDITIVE >>> #{path}"
-
54
n = []
-
54
rest = MultiplicativeExpr( path, n )
-
#puts "ADDITIVE <<< #{rest}"
-
54
if rest != path
-
54
while rest =~ /^\s*(\+| -)\s*/
-
if $1[0] == ?+
-
n = [ :plus, n, [] ]
-
else
-
n = [ :minus, n, [] ]
-
end
-
rest = MultiplicativeExpr( $', n[-1] )
-
end
-
end
-
54
if parsed.size == 0 and n.size != 0
-
54
parsed.replace(n)
-
elsif n.size > 0
-
parsed << n
-
end
-
54
rest
-
end
-
-
#| MultiplicativeExpr ('*' | S ('div' | 'mod') S) UnaryExpr
-
#| UnaryExpr
-
1
def MultiplicativeExpr path, parsed
-
#puts "MULT >>> #{path}"
-
54
n = []
-
54
rest = UnaryExpr( path, n )
-
#puts "MULT <<< #{rest}"
-
54
if rest != path
-
54
while rest =~ /^\s*(\*| div | mod )\s*/
-
if $1[0] == ?*
-
n = [ :mult, n, [] ]
-
elsif $1.include?( "div" )
-
n = [ :div, n, [] ]
-
else
-
n = [ :mod, n, [] ]
-
end
-
rest = UnaryExpr( $', n[-1] )
-
end
-
end
-
54
if parsed.size == 0 and n.size != 0
-
54
parsed.replace(n)
-
elsif n.size > 0
-
parsed << n
-
end
-
54
rest
-
end
-
-
#| '-' UnaryExpr
-
#| UnionExpr
-
1
def UnaryExpr path, parsed
-
54
path =~ /^(\-*)/
-
54
path = $'
-
54
if $1 and (($1.size % 2) != 0)
-
mult = -1
-
else
-
54
mult = 1
-
end
-
54
parsed << :neg if mult < 0
-
-
#puts "UNARY >>> #{path}"
-
54
n = []
-
54
path = UnionExpr( path, n )
-
#puts "UNARY <<< #{path}"
-
54
parsed.concat( n )
-
54
path
-
end
-
-
#| UnionExpr '|' PathExpr
-
#| PathExpr
-
1
def UnionExpr path, parsed
-
#puts "UNION >>> #{path}"
-
54
n = []
-
54
rest = PathExpr( path, n )
-
#puts "UNION <<< #{rest}"
-
54
if rest != path
-
54
while rest =~ /^\s*(\|)\s*/
-
n = [ :union, n, [] ]
-
rest = PathExpr( $', n[-1] )
-
end
-
end
-
54
if parsed.size == 0 and n.size != 0
-
54
parsed.replace( n )
-
elsif n.size > 0
-
parsed << n
-
end
-
54
rest
-
end
-
-
#| LocationPath
-
#| FilterExpr ('/' | '//') RelativeLocationPath
-
1
def PathExpr path, parsed
-
54
path =~ /^\s*/
-
54
path = $'
-
#puts "PATH >>> #{path}"
-
54
n = []
-
54
rest = FilterExpr( path, n )
-
#puts "PATH <<< '#{rest}'"
-
54
if rest != path
-
if rest and rest[0] == ?/
-
return RelativeLocationPath(rest, n)
-
end
-
end
-
#puts "BEFORE WITH '#{rest}'"
-
54
rest = LocationPath(rest, n) if rest =~ /\A[\/\.\@\[\w*]/
-
54
parsed.concat(n)
-
54
return rest
-
end
-
-
#| FilterExpr Predicate
-
#| PrimaryExpr
-
1
def FilterExpr path, parsed
-
#puts "FILTER >>> #{path}"
-
54
n = []
-
54
path = PrimaryExpr( path, n )
-
#puts "FILTER <<< #{path}"
-
54
path = Predicate(path, n) if path and path[0] == ?[
-
#puts "FILTER <<< #{path}"
-
54
parsed.concat(n)
-
54
path
-
end
-
-
#| VARIABLE_REFERENCE
-
#| '(' expr ')'
-
#| LITERAL
-
#| NUMBER
-
#| FunctionCall
-
1
VARIABLE_REFERENCE = /^\$(#{NAME_STR})/u
-
1
NUMBER = /^(\d*\.?\d+)/
-
1
NT = /^comment|text|processing-instruction|node$/
-
1
def PrimaryExpr path, parsed
-
54
case path
-
when VARIABLE_REFERENCE
-
varname = $1
-
path = $'
-
parsed << :variable
-
parsed << varname
-
#arry << @variables[ varname ]
-
when /^(\w[-\w]*)(?:\()/
-
#puts "PrimaryExpr :: Function >>> #$1 -- '#$''"
-
fname = $1
-
tmp = $'
-
#puts "#{fname} =~ #{NT.inspect}"
-
return path if fname =~ NT
-
path = tmp
-
parsed << :function
-
parsed << fname
-
path = FunctionCall(path, parsed)
-
when NUMBER
-
#puts "LITERAL or NUMBER: #$1"
-
varname = $1.nil? ? $2 : $1
-
path = $'
-
parsed << :literal
-
parsed << (varname.include?('.') ? varname.to_f : varname.to_i)
-
when LITERAL
-
#puts "LITERAL or NUMBER: #$1"
-
varname = $1.nil? ? $2 : $1
-
path = $'
-
parsed << :literal
-
parsed << varname
-
when /^\(/ #/
-
path, contents = get_group(path)
-
contents = contents[1..-2]
-
n = []
-
OrExpr( contents, n )
-
parsed.concat(n)
-
end
-
54
path
-
end
-
-
#| FUNCTION_NAME '(' ( expr ( ',' expr )* )? ')'
-
1
def FunctionCall rest, parsed
-
path, arguments = parse_args(rest)
-
argset = []
-
for argument in arguments
-
args = []
-
OrExpr( argument, args )
-
argset << args
-
end
-
parsed << argset
-
path
-
end
-
-
# get_group( '[foo]bar' ) -> ['bar', '[foo]']
-
1
def get_group string
-
ind = 0
-
depth = 0
-
st = string[0,1]
-
en = (st == "(" ? ")" : "]")
-
begin
-
case string[ind,1]
-
when st
-
depth += 1
-
when en
-
depth -= 1
-
end
-
ind += 1
-
end while depth > 0 and ind < string.length
-
return nil unless depth==0
-
[string[ind..-1], string[0..ind-1]]
-
end
-
-
1
def parse_args( string )
-
arguments = []
-
ind = 0
-
inquot = false
-
inapos = false
-
depth = 1
-
begin
-
case string[ind]
-
when ?"
-
inquot = !inquot unless inapos
-
when ?'
-
inapos = !inapos unless inquot
-
else
-
unless inquot or inapos
-
case string[ind]
-
when ?(
-
depth += 1
-
if depth == 1
-
string = string[1..-1]
-
ind -= 1
-
end
-
when ?)
-
depth -= 1
-
if depth == 0
-
s = string[0,ind].strip
-
arguments << s unless s == ""
-
string = string[ind+1..-1]
-
end
-
when ?,
-
if depth == 1
-
s = string[0,ind].strip
-
arguments << s unless s == ""
-
string = string[ind+1..-1]
-
ind = -1
-
end
-
end
-
end
-
end
-
ind += 1
-
end while depth > 0 and ind < string.length
-
return nil unless depth==0
-
[string,arguments]
-
end
-
end
-
end
-
end
-
# -*- encoding: utf-8 -*-
-
# REXML is an XML toolkit for Ruby[http://www.ruby-lang.org], in Ruby.
-
#
-
# REXML is a _pure_ Ruby, XML 1.0 conforming,
-
# non-validating[http://www.w3.org/TR/2004/REC-xml-20040204/#sec-conformance]
-
# toolkit with an intuitive API. REXML passes 100% of the non-validating Oasis
-
# tests[http://www.oasis-open.org/committees/xml-conformance/xml-test-suite.shtml],
-
# and provides tree, stream, SAX2, pull, and lightweight APIs. REXML also
-
# includes a full XPath[http://www.w3c.org/tr/xpath] 1.0 implementation. Since
-
# Ruby 1.8, REXML is included in the standard Ruby distribution.
-
#
-
# Main page:: http://www.germane-software.com/software/rexml
-
# Author:: Sean Russell <serATgermaneHYPHENsoftwareDOTcom>
-
# Date:: 2008/019
-
# Version:: 3.1.7.3
-
#
-
# This API documentation can be downloaded from the REXML home page, or can
-
# be accessed online[http://www.germane-software.com/software/rexml_doc]
-
#
-
# A tutorial is available in the REXML distribution in docs/tutorial.html,
-
# or can be accessed
-
# online[http://www.germane-software.com/software/rexml/docs/tutorial.html]
-
1
module REXML
-
1
COPYRIGHT = "Copyright © 2001-2008 Sean Russell <ser@germane-software.com>"
-
1
DATE = "2008/019"
-
1
VERSION = "3.1.7.3"
-
1
REVISION = %w$Revision: 26193 $[1] || ''
-
-
1
Copyright = COPYRIGHT
-
1
Version = VERSION
-
end
-
1
require 'rexml/encoding'
-
-
1
module REXML
-
# Generates Source-s. USE THIS CLASS.
-
1
class SourceFactory
-
# Generates a Source object
-
# @param arg Either a String, or an IO
-
# @return a Source, or nil if a bad argument was given
-
1
def SourceFactory::create_from(arg)
-
if arg.respond_to? :read and
-
51
arg.respond_to? :readline and
-
arg.respond_to? :nil? and
-
arg.respond_to? :eof?
-
51
IOSource.new(arg)
-
elsif arg.respond_to? :to_str
-
require 'stringio'
-
IOSource.new(StringIO.new(arg))
-
elsif arg.kind_of? Source
-
arg
-
else
-
raise "#{arg.class} is not a valid input stream. It must walk \n"+
-
"like either a String, an IO, or a Source."
-
end
-
end
-
end
-
-
# A Source can be searched for patterns, and wraps buffers and other
-
# objects and provides consumption of text
-
1
class Source
-
1
include Encoding
-
# The current buffer (what we're going to read next)
-
1
attr_reader :buffer
-
# The line number of the last consumed text
-
1
attr_reader :line
-
1
attr_reader :encoding
-
-
# Constructor
-
# @param arg must be a String, and should be a valid XML document
-
# @param encoding if non-null, sets the encoding of the source to this
-
# value, overriding all encoding detection
-
1
def initialize(arg, encoding=nil)
-
51
@orig = @buffer = arg
-
51
if encoding
-
self.encoding = encoding
-
else
-
51
self.encoding = check_encoding( @buffer )
-
end
-
51
@line = 0
-
end
-
-
-
# Inherited from Encoding
-
# Overridden to support optimized en/decoding
-
1
def encoding=(enc)
-
52
return unless super
-
51
@line_break = encode( '>' )
-
51
if @encoding != 'UTF-8'
-
@buffer = decode(@buffer)
-
@to_utf = true
-
else
-
51
@to_utf = false
-
51
@buffer.force_encoding ::Encoding::UTF_8
-
end
-
end
-
-
# Scans the source for a given pattern. Note, that this is not your
-
# usual scan() method. For one thing, the pattern argument has some
-
# requirements; for another, the source can be consumed. You can easily
-
# confuse this method. Originally, the patterns were easier
-
# to construct and this method more robust, because this method
-
# generated search regexes on the fly; however, this was
-
# computationally expensive and slowed down the entire REXML package
-
# considerably, since this is by far the most commonly called method.
-
# @param pattern must be a Regexp, and must be in the form of
-
# /^\s*(#{your pattern, with no groups})(.*)/. The first group
-
# will be returned; the second group is used if the consume flag is
-
# set.
-
# @param consume if true, the pattern returned will be consumed, leaving
-
# everything after it in the Source.
-
# @return the pattern, if found, or nil if the Source is empty or the
-
# pattern is not found.
-
1
def scan(pattern, cons=false)
-
return nil if @buffer.nil?
-
rv = @buffer.scan(pattern)
-
@buffer = $' if cons and rv.size>0
-
rv
-
end
-
-
1
def read
-
end
-
-
1
def consume( pattern )
-
@buffer = $' if pattern.match( @buffer )
-
end
-
-
1
def match_to( char, pattern )
-
return pattern.match(@buffer)
-
end
-
-
1
def match_to_consume( char, pattern )
-
md = pattern.match(@buffer)
-
@buffer = $'
-
return md
-
end
-
-
1
def match(pattern, cons=false)
-
md = pattern.match(@buffer)
-
@buffer = $' if cons and md
-
return md
-
end
-
-
# @return true if the Source is exhausted
-
1
def empty?
-
794
@buffer == ""
-
end
-
-
1
def position
-
@orig.index( @buffer )
-
end
-
-
# @return the current line in the source
-
1
def current_line
-
lines = @orig.split
-
res = lines.grep @buffer[0..30]
-
res = res[-1] if res.kind_of? Array
-
lines.index( res ) if res
-
end
-
end
-
-
# A Source that wraps an IO. See the Source class for method
-
# documentation
-
1
class IOSource < Source
-
#attr_reader :block_size
-
-
# block_size has been deprecated
-
1
def initialize(arg, block_size=500, encoding=nil)
-
51
@er_source = @source = arg
-
51
@to_utf = false
-
-
# Determining the encoding is a deceptively difficult issue to resolve.
-
# First, we check the first two bytes for UTF-16. Then we
-
# assume that the encoding is at least ASCII enough for the '>', and
-
# we read until we get one of those. This gives us the XML declaration,
-
# if there is one. If there isn't one, the file MUST be UTF-8, as per
-
# the XML spec. If there is one, we can determine the encoding from
-
# it.
-
51
@buffer = ""
-
51
str = @source.read( 2 ) || ''
-
51
if encoding
-
self.encoding = encoding
-
elsif str[0,2] == "\xfe\xff"
-
@line_break = "\000>"
-
elsif str[0,2] == "\xff\xfe"
-
@line_break = ">\000"
-
elsif str[0,2] == "\xef\xbb"
-
str += @source.read(1)
-
str = '' if (str[2,1] == "\xBF")
-
@line_break = ">"
-
else
-
51
@line_break = ">"
-
end
-
51
super( @source.eof? ? str : str+@source.readline( @line_break ) )
-
-
if !@to_utf and
-
51
@buffer.respond_to?(:force_encoding) and
-
@source.respond_to?(:external_encoding) and
-
@source.external_encoding != ::Encoding::UTF_8
-
51
@force_utf8 = true
-
else
-
@force_utf8 = false
-
end
-
end
-
-
1
def scan(pattern, cons=false)
-
rv = super
-
# You'll notice that this next section is very similar to the same
-
# section in match(), but just a liiittle different. This is
-
# because it is a touch faster to do it this way with scan()
-
# than the way match() does it; enough faster to warrent duplicating
-
# some code
-
if rv.size == 0
-
until @buffer =~ pattern or @source.nil?
-
begin
-
@buffer << readline
-
rescue Iconv::IllegalSequence
-
raise
-
rescue
-
@source = nil
-
end
-
end
-
rv = super
-
end
-
rv.taint
-
rv
-
end
-
-
1
def read
-
362
begin
-
362
@buffer << readline
-
rescue Exception, NameError
-
@source = nil
-
end
-
end
-
-
1
def consume( pattern )
-
match( pattern, true )
-
end
-
-
1
def match( pattern, cons=false )
-
911
rv = pattern.match(@buffer)
-
911
@buffer = $' if cons and rv
-
911
while !rv and @source
-
begin
-
@buffer << readline
-
rv = pattern.match(@buffer)
-
@buffer = $' if cons and rv
-
rescue
-
@source = nil
-
end
-
end
-
911
rv.taint
-
911
rv
-
end
-
-
1
def empty?
-
794
super and ( @source.nil? || @source.eof? )
-
end
-
-
1
def position
-
@er_source.pos rescue 0
-
end
-
-
# @return the current line in the source
-
1
def current_line
-
begin
-
pos = @er_source.pos # The byte position in the source
-
lineno = @er_source.lineno # The XML < position in the source
-
@er_source.rewind
-
line = 0 # The \r\n position in the source
-
begin
-
while @er_source.pos < pos
-
@er_source.readline
-
line += 1
-
end
-
rescue
-
end
-
rescue IOError
-
pos = -1
-
line = -1
-
end
-
[pos, lineno, line]
-
end
-
-
1
private
-
1
def readline
-
362
str = @source.readline(@line_break)
-
362
return nil if str.nil?
-
-
362
if @to_utf
-
decode(str)
-
else
-
362
str.force_encoding(::Encoding::UTF_8) if @force_utf8
-
362
str
-
end
-
end
-
end
-
end
-
1
module REXML
-
1
class SyncEnumerator
-
1
include Enumerable
-
-
# Creates a new SyncEnumerator which enumerates rows of given
-
# Enumerable objects.
-
1
def initialize(*enums)
-
@gens = enums
-
@length = @gens.collect {|x| x.size }.max
-
end
-
-
# Returns the number of enumerated Enumerable objects, i.e. the size
-
# of each row.
-
1
def size
-
@gens.size
-
end
-
-
# Returns the number of enumerated Enumerable objects, i.e. the size
-
# of each row.
-
1
def length
-
@gens.length
-
end
-
-
# Enumerates rows of the Enumerable objects.
-
1
def each
-
@length.times {|i|
-
yield @gens.collect {|x| x[i]}
-
}
-
self
-
end
-
end
-
end
-
1
require 'rexml/entity'
-
1
require 'rexml/doctype'
-
1
require 'rexml/child'
-
1
require 'rexml/doctype'
-
1
require 'rexml/parseexception'
-
-
1
module REXML
-
# Represents text nodes in an XML document
-
1
class Text < Child
-
1
include Comparable
-
# The order in which the substitutions occur
-
1
SPECIALS = [ /&(?!#?[\w-]+;)/u, /</u, />/u, /"/u, /'/u, /\r/u ]
-
1
SUBSTITUTES = ['&', '<', '>', '"', ''', ' ']
-
# Characters which are substituted in written strings
-
1
SLAICEPS = [ '<', '>', '"', "'", '&' ]
-
1
SETUTITSBUS = [ /</u, />/u, /"/u, /'/u, /&/u ]
-
-
# If +raw+ is true, then REXML leaves the value alone
-
1
attr_accessor :raw
-
-
1
NEEDS_A_SECOND_CHECK = /(<|&((#{Entity::NAME});|(#0*((?:\d+)|(?:x[a-fA-F0-9]+)));)?)/um
-
1
NUMERICENTITY = /�*((?:\d+)|(?:x[a-fA-F0-9]+));/
-
1
VALID_CHAR = [
-
0x9, 0xA, 0xD,
-
(0x20..0xD7FF),
-
(0xE000..0xFFFD),
-
(0x10000..0x10FFFF)
-
]
-
-
1
if String.method_defined? :encode
-
1
VALID_XML_CHARS = Regexp.new('^['+
-
VALID_CHAR.map { |item|
-
6
case item
-
when Fixnum
-
3
[item].pack('U').force_encoding('utf-8')
-
when Range
-
3
[item.first, '-'.ord, item.last].pack('UUU').force_encoding('utf-8')
-
end
-
}.join +
-
']*$')
-
else
-
VALID_XML_CHARS = /^(
-
[\x09\x0A\x0D\x20-\x7E] # ASCII
-
| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
-
| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
-
| [\xE1-\xEC\xEE][\x80-\xBF]{2} # straight 3-byte
-
| \xEF[\x80-\xBE]{2} #
-
| \xEF\xBF[\x80-\xBD] # excluding U+fffe and U+ffff
-
| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
-
| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
-
| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
-
| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
-
)*$/nx;
-
end
-
-
# Constructor
-
# +arg+ if a String, the content is set to the String. If a Text,
-
# the object is shallowly cloned.
-
#
-
# +respect_whitespace+ (boolean, false) if true, whitespace is
-
# respected
-
#
-
# +parent+ (nil) if this is a Parent object, the parent
-
# will be set to this.
-
#
-
# +raw+ (nil) This argument can be given three values.
-
# If true, then the value of used to construct this object is expected to
-
# contain no unescaped XML markup, and REXML will not change the text. If
-
# this value is false, the string may contain any characters, and REXML will
-
# escape any and all defined entities whose values are contained in the
-
# text. If this value is nil (the default), then the raw value of the
-
# parent will be used as the raw value for this node. If there is no raw
-
# value for the parent, and no value is supplied, the default is false.
-
# Use this field if you have entities defined for some text, and you don't
-
# want REXML to escape that text in output.
-
# Text.new( "<&", false, nil, false ) #-> "<&"
-
# Text.new( "<&", false, nil, false ) #-> "&lt;&amp;"
-
# Text.new( "<&", false, nil, true ) #-> Parse exception
-
# Text.new( "<&", false, nil, true ) #-> "<&"
-
# # Assume that the entity "s" is defined to be "sean"
-
# # and that the entity "r" is defined to be "russell"
-
# Text.new( "sean russell" ) #-> "&s; &r;"
-
# Text.new( "sean russell", false, nil, true ) #-> "sean russell"
-
#
-
# +entity_filter+ (nil) This can be an array of entities to match in the
-
# supplied text. This argument is only useful if +raw+ is set to false.
-
# Text.new( "sean russell", false, nil, false, ["s"] ) #-> "&s; russell"
-
# Text.new( "sean russell", false, nil, true, ["s"] ) #-> "sean russell"
-
# In the last example, the +entity_filter+ argument is ignored.
-
#
-
# +illegal+ INTERNAL USE ONLY
-
1
def initialize(arg, respect_whitespace=false, parent=nil, raw=nil,
-
entity_filter=nil, illegal=NEEDS_A_SECOND_CHECK )
-
-
385
@raw = false
-
385
@parent = nil
-
-
385
if parent
-
super( parent )
-
@raw = parent.raw
-
end
-
-
385
@raw = raw unless raw.nil?
-
385
@entity_filter = entity_filter
-
385
@normalized = @unnormalized = nil
-
-
385
if arg.kind_of? String
-
385
@string = arg.dup
-
385
@string.squeeze!(" \n\t") unless respect_whitespace
-
elsif arg.kind_of? Text
-
@string = arg.to_s
-
@raw = arg.raw
-
elsif
-
raise "Illegal argument of type #{arg.type} for Text constructor (#{arg})"
-
end
-
-
385
@string.gsub!( /\r\n?/, "\n" )
-
-
385
Text.check(@string, illegal, doctype) if @raw
-
end
-
-
1
def parent= parent
-
385
super(parent)
-
385
Text.check(@string, NEEDS_A_SECOND_CHECK, doctype) if @raw and @parent
-
end
-
-
# check for illegal characters
-
1
def Text.check string, pattern, doctype
-
-
# illegal anywhere
-
855
if string !~ VALID_XML_CHARS
-
if String.method_defined? :encode
-
string.chars.each do |c|
-
case c.ord
-
when *VALID_CHAR
-
else
-
raise "Illegal character #{c.inspect} in raw string \"#{string}\""
-
end
-
end
-
else
-
string.scan(/[\x00-\x7F]|[\x80-\xBF][\xC0-\xF0]*|[\xC0-\xF0]/n) do |c|
-
case c.unpack('U')
-
when *VALID_CHAR
-
else
-
raise "Illegal character #{c.inspect} in raw string \"#{string}\""
-
end
-
end
-
end
-
end
-
-
# context sensitive
-
855
string.scan(pattern) do
-
10
if $1[-1] != ?;
-
raise "Illegal character '#{$1}' in raw string \"#{string}\""
-
elsif $1[0] == ?&
-
10
if $5 and $5[0] == ?#
-
case ($5[1] == ?x ? $5[2..-1].to_i(16) : $5[1..-1].to_i)
-
when *VALID_CHAR
-
else
-
raise "Illegal character '#{$1}' in raw string \"#{string}\""
-
end
-
# FIXME: below can't work but this needs API change.
-
# elsif @parent and $3 and !SUBSTITUTES.include?($1)
-
# if !doctype or !doctype.entities.has_key?($3)
-
# raise "Undeclared entity '#{$1}' in raw string \"#{string}\""
-
# end
-
end
-
end
-
end
-
end
-
-
1
def node_type
-
175
:text
-
end
-
-
1
def empty?
-
@string.size==0
-
end
-
-
-
1
def clone
-
return Text.new(self)
-
end
-
-
-
# Appends text to this text node. The text is appended in the +raw+ mode
-
# of this text node.
-
1
def <<( to_append )
-
1
@string << to_append.gsub( /\r\n?/, "\n" )
-
end
-
-
-
# +other+ a String or a Text
-
# +returns+ the result of (to_s <=> arg.to_s)
-
1
def <=>( other )
-
to_s() <=> other.to_s
-
end
-
-
1
def doctype
-
862
if @parent
-
486
doc = @parent.document
-
486
doc.doctype if doc
-
end
-
end
-
-
1
REFERENCE = /#{Entity::REFERENCE}/
-
# Returns the string value of this text node. This string is always
-
# escaped, meaning that it is a valid XML text node string, and all
-
# entities that can be escaped, have been inserted. This method respects
-
# the entity filter set in the constructor.
-
#
-
# # Assume that the entity "s" is defined to be "sean", and that the
-
# # entity "r" is defined to be "russell"
-
# t = Text.new( "< & sean russell", false, nil, false, ['s'] )
-
# t.to_s #-> "< & &s; russell"
-
# t = Text.new( "< & &s; russell", false, nil, false )
-
# t.to_s #-> "< & &s; russell"
-
# u = Text.new( "sean russell", false, nil, true )
-
# u.to_s #-> "sean russell"
-
1
def to_s
-
175
return @string if @raw
-
return @normalized if @normalized
-
-
@normalized = Text::normalize( @string, doctype, @entity_filter )
-
end
-
-
1
def inspect
-
@string.inspect
-
end
-
-
# Returns the string value of this text. This is the text without
-
# entities, as it might be used programmatically, or printed to the
-
# console. This ignores the 'raw' attribute setting, and any
-
# entity_filter.
-
#
-
# # Assume that the entity "s" is defined to be "sean", and that the
-
# # entity "r" is defined to be "russell"
-
# t = Text.new( "< & sean russell", false, nil, false, ['s'] )
-
# t.value #-> "< & sean russell"
-
# t = Text.new( "< & &s; russell", false, nil, false )
-
# t.value #-> "< & sean russell"
-
# u = Text.new( "sean russell", false, nil, true )
-
# u.value #-> "sean russell"
-
1
def value
-
210
return @unnormalized if @unnormalized
-
110
@unnormalized = Text::unnormalize( @string, doctype )
-
end
-
-
# Sets the contents of this text node. This expects the text to be
-
# unnormalized. It returns self.
-
#
-
# e = Element.new( "a" )
-
# e.add_text( "foo" ) # <a>foo</a>
-
# e[0].value = "bar" # <a>bar</a>
-
# e[0].value = "<a>" # <a><a></a>
-
1
def value=( val )
-
@string = val.gsub( /\r\n?/, "\n" )
-
@unnormalized = nil
-
@normalized = nil
-
@raw = false
-
end
-
-
1
def wrap(string, width, addnewline=false)
-
# Recursively wrap string at width.
-
return string if string.length <= width
-
place = string.rindex(' ', width) # Position in string with last ' ' before cutoff
-
if addnewline then
-
return "\n" + string[0,place] + "\n" + wrap(string[place+1..-1], width)
-
else
-
return string[0,place] + "\n" + wrap(string[place+1..-1], width)
-
end
-
end
-
-
1
def indent_text(string, level=1, style="\t", indentfirstline=true)
-
return string if level < 0
-
new_string = ''
-
string.each_line { |line|
-
indent_string = style * level
-
new_line = (indent_string + line).sub(/[\s]+$/,'')
-
new_string << new_line
-
}
-
new_string.strip! unless indentfirstline
-
return new_string
-
end
-
-
# == DEPRECATED
-
# See REXML::Formatters
-
#
-
1
def write( writer, indent=-1, transitive=false, ie_hack=false )
-
Kernel.warn("#{self.class.name}.write is deprecated. See REXML::Formatters")
-
formatter = if indent > -1
-
REXML::Formatters::Pretty.new( indent )
-
else
-
REXML::Formatters::Default.new
-
end
-
formatter.write( self, writer )
-
end
-
-
# FIXME
-
# This probably won't work properly
-
1
def xpath
-
path = @parent.xpath
-
path += "/text()"
-
return path
-
end
-
-
# Writes out text, substituting special characters beforehand.
-
# +out+ A String, IO, or any other object supporting <<( String )
-
# +input+ the text to substitute and the write out
-
#
-
# z=utf8.unpack("U*")
-
# ascOut=""
-
# z.each{|r|
-
# if r < 0x100
-
# ascOut.concat(r.chr)
-
# else
-
# ascOut.concat(sprintf("&#x%x;", r))
-
# end
-
# }
-
# puts ascOut
-
1
def write_with_substitution out, input
-
copy = input.clone
-
# Doing it like this rather than in a loop improves the speed
-
copy.gsub!( SPECIALS[0], SUBSTITUTES[0] )
-
copy.gsub!( SPECIALS[1], SUBSTITUTES[1] )
-
copy.gsub!( SPECIALS[2], SUBSTITUTES[2] )
-
copy.gsub!( SPECIALS[3], SUBSTITUTES[3] )
-
copy.gsub!( SPECIALS[4], SUBSTITUTES[4] )
-
copy.gsub!( SPECIALS[5], SUBSTITUTES[5] )
-
out << copy
-
end
-
-
# Reads text, substituting entities
-
1
def Text::read_with_substitution( input, illegal=nil )
-
copy = input.clone
-
-
if copy =~ illegal
-
raise ParseException.new( "malformed text: Illegal character #$& in \"#{copy}\"" )
-
end if illegal
-
-
copy.gsub!( /\r\n?/, "\n" )
-
if copy.include? ?&
-
copy.gsub!( SETUTITSBUS[0], SLAICEPS[0] )
-
copy.gsub!( SETUTITSBUS[1], SLAICEPS[1] )
-
copy.gsub!( SETUTITSBUS[2], SLAICEPS[2] )
-
copy.gsub!( SETUTITSBUS[3], SLAICEPS[3] )
-
copy.gsub!( SETUTITSBUS[4], SLAICEPS[4] )
-
copy.gsub!( /�*((?:\d+)|(?:x[a-f0-9]+));/ ) {
-
m=$1
-
#m='0' if m==''
-
m = "0#{m}" if m[0] == ?x
-
[Integer(m)].pack('U*')
-
}
-
end
-
copy
-
end
-
-
1
EREFERENCE = /&(?!#{Entity::NAME};)/
-
# Escapes all possible entities
-
1
def Text::normalize( input, doctype=nil, entity_filter=nil )
-
copy = input.to_s
-
# Doing it like this rather than in a loop improves the speed
-
#copy = copy.gsub( EREFERENCE, '&' )
-
copy = copy.gsub( "&", "&" )
-
if doctype
-
# Replace all ampersands that aren't part of an entity
-
doctype.entities.each_value do |entity|
-
copy = copy.gsub( entity.value,
-
"&#{entity.name};" ) if entity.value and
-
not( entity_filter and entity_filter.include?(entity) )
-
end
-
else
-
# Replace all ampersands that aren't part of an entity
-
DocType::DEFAULT_ENTITIES.each_value do |entity|
-
copy = copy.gsub(entity.value, "&#{entity.name};" )
-
end
-
end
-
copy
-
end
-
-
# Unescapes all possible entities
-
1
def Text::unnormalize( string, doctype=nil, filter=nil, illegal=nil )
-
10213
string.gsub( /\r\n?/, "\n" ).gsub( REFERENCE ) {
-
10005
ref = $&
-
10005
if ref[1] == ?#
-
if ref[2] == ?x
-
[ref[3...-1].to_i(16)].pack('U*')
-
else
-
[ref[2...-1].to_i].pack('U*')
-
end
-
elsif ref == '&'
-
4
'&'
-
elsif filter and filter.include?( ref[1...-1] )
-
ref
-
elsif doctype
-
10001
doctype.entity( ref[1...-1] ) or ref
-
else
-
entity_value = DocType::DEFAULT_ENTITIES[ ref[1...-1] ]
-
entity_value ? entity_value.value : ref
-
end
-
}
-
end
-
end
-
end
-
1
require 'rexml/parseexception'
-
1
module REXML
-
1
class UndefinedNamespaceException < ParseException
-
1
def initialize( prefix, source, parser )
-
super( "Undefined prefix #{prefix} found" )
-
end
-
end
-
end
-
1
module REXML
-
1
module Validation
-
1
class ValidationException < RuntimeError
-
1
def initialize msg
-
super
-
end
-
end
-
end
-
end
-
1
require 'rexml/encoding'
-
1
require 'rexml/source'
-
-
1
module REXML
-
# NEEDS DOCUMENTATION
-
1
class XMLDecl < Child
-
1
include Encoding
-
-
1
DEFAULT_VERSION = "1.0";
-
1
DEFAULT_ENCODING = "UTF-8";
-
1
DEFAULT_STANDALONE = "no";
-
1
START = '<\?xml';
-
1
STOP = '\?>';
-
-
1
attr_accessor :version, :standalone
-
1
attr_reader :writeencoding, :writethis
-
-
1
def initialize(version=DEFAULT_VERSION, encoding=nil, standalone=nil)
-
2
@writethis = true
-
2
@writeencoding = !encoding.nil?
-
2
if version.kind_of? XMLDecl
-
super()
-
@version = version.version
-
self.encoding = version.encoding
-
@writeencoding = version.writeencoding
-
@standalone = version.standalone
-
else
-
2
super()
-
2
@version = version
-
2
self.encoding = encoding
-
2
@standalone = standalone
-
end
-
2
@version = DEFAULT_VERSION if @version.nil?
-
end
-
-
1
def clone
-
XMLDecl.new(self)
-
end
-
-
# indent::
-
# Ignored. There must be no whitespace before an XML declaration
-
# transitive::
-
# Ignored
-
# ie_hack::
-
# Ignored
-
1
def write(writer, indent=-1, transitive=false, ie_hack=false)
-
return nil unless @writethis or writer.kind_of? Output
-
writer << START.sub(/\\/u, '')
-
if writer.kind_of? Output
-
writer << " #{content writer.encoding}"
-
else
-
writer << " #{content encoding}"
-
end
-
writer << STOP.sub(/\\/u, '')
-
end
-
-
1
def ==( other )
-
other.kind_of?(XMLDecl) and
-
other.version == @version and
-
other.encoding == self.encoding and
-
other.standalone == @standalone
-
end
-
-
1
def xmldecl version, encoding, standalone
-
@version = version
-
self.encoding = encoding
-
@standalone = standalone
-
end
-
-
1
def node_type
-
:xmldecl
-
end
-
-
1
alias :stand_alone? :standalone
-
1
alias :old_enc= :encoding=
-
-
1
def encoding=( enc )
-
2
if enc.nil?
-
1
self.old_enc = "UTF-8"
-
1
@writeencoding = false
-
else
-
1
self.old_enc = enc
-
1
@writeencoding = true
-
end
-
2
self.dowrite
-
end
-
-
# Only use this if you do not want the XML declaration to be written;
-
# this object is ignored by the XML writer. Otherwise, instantiate your
-
# own XMLDecl and add it to the document.
-
#
-
# Note that XML 1.1 documents *must* include an XML declaration
-
1
def XMLDecl.default
-
1
rv = XMLDecl.new( "1.0" )
-
1
rv.nowrite
-
1
rv
-
end
-
-
1
def nowrite
-
1
@writethis = false
-
end
-
-
1
def dowrite
-
2
@writethis = true
-
end
-
-
1
def inspect
-
START.sub(/\\/u, '') + " ... " + STOP.sub(/\\/u, '')
-
end
-
-
1
private
-
1
def content(enc)
-
rv = "version='#@version'"
-
rv << " encoding='#{enc}'" if @writeencoding || enc !~ /utf-8/i
-
rv << " standalone='#@standalone'" if @standalone
-
rv
-
end
-
end
-
end
-
1
module REXML
-
# Defines a number of tokens used for parsing XML. Not for general
-
# consumption.
-
1
module XMLTokens
-
1
NCNAME_STR= '[\w:][\-\w.]*'
-
1
NAME_STR= "(?:#{NCNAME_STR}:)?#{NCNAME_STR}"
-
-
1
NAMECHAR = '[\-\w\.:]'
-
1
NAME = "([\\w:]#{NAMECHAR}*)"
-
1
NMTOKEN = "(?:#{NAMECHAR})+"
-
1
NMTOKENS = "#{NMTOKEN}(\\s+#{NMTOKEN})*"
-
1
REFERENCE = "(?:&#{NAME};|&#\\d+;|&#x[0-9a-fA-F]+;)"
-
-
#REFERENCE = "(?:#{ENTITYREF}|#{CHARREF})"
-
#ENTITYREF = "&#{NAME};"
-
#CHARREF = "&#\\d+;|&#x[0-9a-fA-F]+;"
-
end
-
end
-
1
require 'rexml/functions'
-
1
require 'rexml/xpath_parser'
-
-
1
module REXML
-
# Wrapper class. Use this class to access the XPath functions.
-
1
class XPath
-
1
include Functions
-
# A base Hash object, supposing to be used when initializing a
-
# default empty namespaces set, but is currently unused.
-
# TODO: either set the namespaces=EMPTY_HASH, or deprecate this.
-
1
EMPTY_HASH = {}
-
-
# Finds and returns the first node that matches the supplied xpath.
-
# element::
-
# The context element
-
# path::
-
# The xpath to search for. If not supplied or nil, returns the first
-
# node matching '*'.
-
# namespaces::
-
# If supplied, a Hash which defines a namespace mapping.
-
# variables::
-
# If supplied, a Hash which maps $variables in the query
-
# to values. This can be used to avoid XPath injection attacks
-
# or to automatically handle escaping string values.
-
#
-
# XPath.first( node )
-
# XPath.first( doc, "//b"} )
-
# XPath.first( node, "a/x:b", { "x"=>"http://doofus" } )
-
# XPath.first( node, '/book/publisher/text()=$publisher', {}, {"publisher"=>"O'Reilly"})
-
1
def XPath::first element, path=nil, namespaces=nil, variables={}
-
raise "The namespaces argument, if supplied, must be a hash object." unless namespaces.nil? or namespaces.kind_of?(Hash)
-
raise "The variables argument, if supplied, must be a hash object." unless variables.kind_of?(Hash)
-
parser = XPathParser.new
-
parser.namespaces = namespaces
-
parser.variables = variables
-
path = "*" unless path
-
element = [element] unless element.kind_of? Array
-
parser.parse(path, element).flatten[0]
-
end
-
-
# Iterates over nodes that match the given path, calling the supplied
-
# block with the match.
-
# element::
-
# The context element
-
# path::
-
# The xpath to search for. If not supplied or nil, defaults to '*'
-
# namespaces::
-
# If supplied, a Hash which defines a namespace mapping
-
# variables::
-
# If supplied, a Hash which maps $variables in the query
-
# to values. This can be used to avoid XPath injection attacks
-
# or to automatically handle escaping string values.
-
#
-
# XPath.each( node ) { |el| ... }
-
# XPath.each( node, '/*[@attr='v']' ) { |el| ... }
-
# XPath.each( node, 'ancestor::x' ) { |el| ... }
-
# XPath.each( node, '/book/publisher/text()=$publisher', {}, {"publisher"=>"O'Reilly"}) \
-
# {|el| ... }
-
1
def XPath::each element, path=nil, namespaces=nil, variables={}, &block
-
54
raise "The namespaces argument, if supplied, must be a hash object." unless namespaces.nil? or namespaces.kind_of?(Hash)
-
54
raise "The variables argument, if supplied, must be a hash object." unless variables.kind_of?(Hash)
-
54
parser = XPathParser.new
-
54
parser.namespaces = namespaces
-
54
parser.variables = variables
-
54
path = "*" unless path
-
54
element = [element] unless element.kind_of? Array
-
54
parser.parse(path, element).each( &block )
-
end
-
-
# Returns an array of nodes matching a given XPath.
-
1
def XPath::match element, path=nil, namespaces=nil, variables={}
-
parser = XPathParser.new
-
parser.namespaces = namespaces
-
parser.variables = variables
-
path = "*" unless path
-
element = [element] unless element.kind_of? Array
-
parser.parse(path,element)
-
end
-
end
-
end
-
1
require 'rexml/namespace'
-
1
require 'rexml/xmltokens'
-
1
require 'rexml/attribute'
-
1
require 'rexml/syncenumerator'
-
1
require 'rexml/parsers/xpathparser'
-
-
1
class Object
-
# provides a unified +clone+ operation, for REXML::XPathParser
-
# to use across multiple Object types
-
1
def dclone
-
clone
-
end
-
end
-
1
class Symbol
-
# provides a unified +clone+ operation, for REXML::XPathParser
-
# to use across multiple Object types
-
1
def dclone ; self ; end
-
end
-
1
class Fixnum
-
# provides a unified +clone+ operation, for REXML::XPathParser
-
# to use across multiple Object types
-
1
def dclone ; self ; end
-
end
-
1
class Float
-
# provides a unified +clone+ operation, for REXML::XPathParser
-
# to use across multiple Object types
-
1
def dclone ; self ; end
-
end
-
1
class Array
-
# provides a unified +clone+ operation, for REXML::XPathParser
-
# to use across multiple Object+ types
-
1
def dclone
-
klone = self.clone
-
klone.clear
-
self.each{|v| klone << v.dclone}
-
klone
-
end
-
end
-
-
1
module REXML
-
# You don't want to use this class. Really. Use XPath, which is a wrapper
-
# for this class. Believe me. You don't want to poke around in here.
-
# There is strange, dark magic at work in this code. Beware. Go back! Go
-
# back while you still can!
-
1
class XPathParser
-
1
include XMLTokens
-
1
LITERAL = /^'([^']*)'|^"([^"]*)"/u
-
-
1
def initialize( )
-
54
@parser = REXML::Parsers::XPathParser.new
-
54
@namespaces = nil
-
54
@variables = {}
-
end
-
-
1
def namespaces=( namespaces={} )
-
54
Functions::namespace_context = namespaces
-
54
@namespaces = namespaces
-
end
-
-
1
def variables=( vars={} )
-
54
Functions::variables = vars
-
54
@variables = vars
-
end
-
-
1
def parse path, nodeset
-
#puts "#"*40
-
54
path_stack = @parser.parse( path )
-
#puts "PARSE: #{path} => #{path_stack.inspect}"
-
#puts "PARSE: nodeset = #{nodeset.inspect}"
-
54
match( path_stack, nodeset )
-
end
-
-
1
def get_first path, nodeset
-
#puts "#"*40
-
path_stack = @parser.parse( path )
-
#puts "PARSE: #{path} => #{path_stack.inspect}"
-
#puts "PARSE: nodeset = #{nodeset.inspect}"
-
first( path_stack, nodeset )
-
end
-
-
1
def predicate path, nodeset
-
path_stack = @parser.parse( path )
-
expr( path_stack, nodeset )
-
end
-
-
1
def []=( variable_name, value )
-
@variables[ variable_name ] = value
-
end
-
-
-
# Performs a depth-first (document order) XPath search, and returns the
-
# first match. This is the fastest, lightest way to return a single result.
-
#
-
# FIXME: This method is incomplete!
-
1
def first( path_stack, node )
-
#puts "#{depth}) Entering match( #{path.inspect}, #{tree.inspect} )"
-
return nil if path.size == 0
-
-
case path[0]
-
when :document
-
# do nothing
-
return first( path[1..-1], node )
-
when :child
-
for c in node.children
-
#puts "#{depth}) CHILD checking #{name(c)}"
-
r = first( path[1..-1], c )
-
#puts "#{depth}) RETURNING #{r.inspect}" if r
-
return r if r
-
end
-
when :qname
-
name = path[2]
-
#puts "#{depth}) QNAME #{name(tree)} == #{name} (path => #{path.size})"
-
if node.name == name
-
#puts "#{depth}) RETURNING #{tree.inspect}" if path.size == 3
-
return node if path.size == 3
-
return first( path[3..-1], node )
-
else
-
return nil
-
end
-
when :descendant_or_self
-
r = first( path[1..-1], node )
-
return r if r
-
for c in node.children
-
r = first( path, c )
-
return r if r
-
end
-
when :node
-
return first( path[1..-1], node )
-
when :any
-
return first( path[1..-1], node )
-
end
-
return nil
-
end
-
-
-
1
def match( path_stack, nodeset )
-
#puts "MATCH: path_stack = #{path_stack.inspect}"
-
#puts "MATCH: nodeset = #{nodeset.inspect}"
-
54
r = expr( path_stack, nodeset )
-
#puts "MAIN EXPR => #{r.inspect}"
-
54
r
-
end
-
-
1
private
-
-
-
# Returns a String namespace for a node, given a prefix
-
# The rules are:
-
#
-
# 1. Use the supplied namespace mapping first.
-
# 2. If no mapping was supplied, use the context node to look up the namespace
-
1
def get_namespace( node, prefix )
-
if @namespaces
-
return @namespaces[prefix] || ''
-
else
-
return node.namespace( prefix ) if node.node_type == :element
-
return ''
-
end
-
end
-
-
-
# Expr takes a stack of path elements and a set of nodes (either a Parent
-
# or an Array and returns an Array of matching nodes
-
1
ALL = [ :attribute, :element, :text, :processing_instruction, :comment ]
-
1
ELEMENTS = [ :element ]
-
1
def expr( path_stack, nodeset, context=nil )
-
#puts "#"*15
-
#puts "In expr with #{path_stack.inspect}"
-
#puts "Returning" if path_stack.length == 0 || nodeset.length == 0
-
54
node_types = ELEMENTS
-
54
return nodeset if path_stack.length == 0 || nodeset.length == 0
-
54
while path_stack.length > 0
-
#puts "#"*5
-
#puts "Path stack = #{path_stack.inspect}"
-
#puts "Nodeset is #{nodeset.inspect}"
-
108
if nodeset.length == 0
-
path_stack.clear
-
return []
-
end
-
108
case (op = path_stack.shift)
-
when :document
-
nodeset = [ nodeset[0].root_node ]
-
#puts ":document, nodeset = #{nodeset.inspect}"
-
-
when :qname
-
#puts "IN QNAME"
-
prefix = path_stack.shift
-
name = path_stack.shift
-
nodeset.delete_if do |node|
-
# FIXME: This DOUBLES the time XPath searches take
-
ns = get_namespace( node, prefix )
-
#puts "NS = #{ns.inspect}"
-
#puts "node.node_type == :element => #{node.node_type == :element}"
-
if node.node_type == :element
-
#puts "node.name == #{name} => #{node.name == name}"
-
if node.name == name
-
#puts "node.namespace == #{ns.inspect} => #{node.namespace == ns}"
-
end
-
end
-
!(node.node_type == :element and
-
node.name == name and
-
node.namespace == ns )
-
end
-
node_types = ELEMENTS
-
-
when :any
-
#puts "ANY 1: nodeset = #{nodeset.inspect}"
-
#puts "ANY 1: node_types = #{node_types.inspect}"
-
358
nodeset.delete_if { |node| !node_types.include?(node.node_type) }
-
#puts "ANY 2: nodeset = #{nodeset.inspect}"
-
-
when :self
-
# This space left intentionally blank
-
-
when :processing_instruction
-
target = path_stack.shift
-
nodeset.delete_if do |node|
-
(node.node_type != :processing_instruction) or
-
( target!='' and ( node.target != target ) )
-
end
-
-
when :text
-
nodeset.delete_if { |node| node.node_type != :text }
-
-
when :comment
-
nodeset.delete_if { |node| node.node_type != :comment }
-
-
when :node
-
# This space left intentionally blank
-
node_types = ALL
-
-
when :child
-
54
new_nodeset = []
-
54
nt = nil
-
54
nodeset.each do |node|
-
54
nt = node.node_type
-
54
new_nodeset += node.children if nt == :element or nt == :document
-
end
-
54
nodeset = new_nodeset
-
54
node_types = ELEMENTS
-
-
when :literal
-
return path_stack.shift
-
-
when :attribute
-
new_nodeset = []
-
case path_stack.shift
-
when :qname
-
prefix = path_stack.shift
-
name = path_stack.shift
-
for element in nodeset
-
if element.node_type == :element
-
#puts "Element name = #{element.name}"
-
#puts "get_namespace( #{element.inspect}, #{prefix} ) = #{get_namespace(element, prefix)}"
-
attrib = element.attribute( name, get_namespace(element, prefix) )
-
#puts "attrib = #{attrib.inspect}"
-
new_nodeset << attrib if attrib
-
end
-
end
-
when :any
-
#puts "ANY"
-
for element in nodeset
-
if element.node_type == :element
-
new_nodeset += element.attributes.to_a
-
end
-
end
-
end
-
nodeset = new_nodeset
-
-
when :parent
-
#puts "PARENT 1: nodeset = #{nodeset}"
-
nodeset = nodeset.collect{|n| n.parent}.compact
-
#nodeset = expr(path_stack.dclone, nodeset.collect{|n| n.parent}.compact)
-
#puts "PARENT 2: nodeset = #{nodeset.inspect}"
-
node_types = ELEMENTS
-
-
when :ancestor
-
new_nodeset = []
-
nodeset.each do |node|
-
while node.parent
-
node = node.parent
-
new_nodeset << node unless new_nodeset.include? node
-
end
-
end
-
nodeset = new_nodeset
-
node_types = ELEMENTS
-
-
when :ancestor_or_self
-
new_nodeset = []
-
nodeset.each do |node|
-
if node.node_type == :element
-
new_nodeset << node
-
while ( node.parent )
-
node = node.parent
-
new_nodeset << node unless new_nodeset.include? node
-
end
-
end
-
end
-
nodeset = new_nodeset
-
node_types = ELEMENTS
-
-
when :predicate
-
new_nodeset = []
-
subcontext = { :size => nodeset.size }
-
pred = path_stack.shift
-
nodeset.each_with_index { |node, index|
-
subcontext[ :node ] = node
-
#puts "PREDICATE SETTING CONTEXT INDEX TO #{index+1}"
-
subcontext[ :index ] = index+1
-
pc = pred.dclone
-
#puts "#{node.hash}) Recursing with #{pred.inspect} and [#{node.inspect}]"
-
result = expr( pc, [node], subcontext )
-
result = result[0] if result.kind_of? Array and result.length == 1
-
#puts "#{node.hash}) Result = #{result.inspect} (#{result.class.name})"
-
if result.kind_of? Numeric
-
#puts "Adding node #{node.inspect}" if result == (index+1)
-
new_nodeset << node if result == (index+1)
-
elsif result.instance_of? Array
-
if result.size > 0 and result.inject(false) {|k,s| s or k}
-
#puts "Adding node #{node.inspect}" if result.size > 0
-
new_nodeset << node if result.size > 0
-
end
-
else
-
#puts "Adding node #{node.inspect}" if result
-
new_nodeset << node if result
-
end
-
}
-
#puts "New nodeset = #{new_nodeset.inspect}"
-
#puts "Path_stack = #{path_stack.inspect}"
-
nodeset = new_nodeset
-
=begin
-
predicate = path_stack.shift
-
ns = nodeset.clone
-
result = expr( predicate, ns )
-
#puts "Result = #{result.inspect} (#{result.class.name})"
-
#puts "nodeset = #{nodeset.inspect}"
-
if result.kind_of? Array
-
nodeset = result.zip(ns).collect{|m,n| n if m}.compact
-
else
-
nodeset = result ? nodeset : []
-
end
-
#puts "Outgoing NS = #{nodeset.inspect}"
-
=end
-
-
when :descendant_or_self
-
rv = descendant_or_self( path_stack, nodeset )
-
path_stack.clear
-
nodeset = rv
-
node_types = ELEMENTS
-
-
when :descendant
-
results = []
-
nt = nil
-
nodeset.each do |node|
-
nt = node.node_type
-
results += expr( path_stack.dclone.unshift( :descendant_or_self ),
-
node.children ) if nt == :element or nt == :document
-
end
-
nodeset = results
-
node_types = ELEMENTS
-
-
when :following_sibling
-
#puts "FOLLOWING_SIBLING 1: nodeset = #{nodeset}"
-
results = []
-
nodeset.each do |node|
-
next if node.parent.nil?
-
all_siblings = node.parent.children
-
current_index = all_siblings.index( node )
-
following_siblings = all_siblings[ current_index+1 .. -1 ]
-
results += expr( path_stack.dclone, following_siblings )
-
end
-
#puts "FOLLOWING_SIBLING 2: nodeset = #{nodeset}"
-
nodeset = results
-
-
when :preceding_sibling
-
results = []
-
nodeset.each do |node|
-
next if node.parent.nil?
-
all_siblings = node.parent.children
-
current_index = all_siblings.index( node )
-
preceding_siblings = all_siblings[ 0, current_index ].reverse
-
results += preceding_siblings
-
end
-
nodeset = results
-
node_types = ELEMENTS
-
-
when :preceding
-
new_nodeset = []
-
nodeset.each do |node|
-
new_nodeset += preceding( node )
-
end
-
#puts "NEW NODESET => #{new_nodeset.inspect}"
-
nodeset = new_nodeset
-
node_types = ELEMENTS
-
-
when :following
-
new_nodeset = []
-
nodeset.each do |node|
-
new_nodeset += following( node )
-
end
-
nodeset = new_nodeset
-
node_types = ELEMENTS
-
-
when :namespace
-
#puts "In :namespace"
-
new_nodeset = []
-
prefix = path_stack.shift
-
nodeset.each do |node|
-
if (node.node_type == :element or node.node_type == :attribute)
-
if @namespaces
-
namespaces = @namespaces
-
elsif (node.node_type == :element)
-
namespaces = node.namespaces
-
else
-
namespaces = node.element.namesapces
-
end
-
#puts "Namespaces = #{namespaces.inspect}"
-
#puts "Prefix = #{prefix.inspect}"
-
#puts "Node.namespace = #{node.namespace}"
-
if (node.namespace == namespaces[prefix])
-
new_nodeset << node
-
end
-
end
-
end
-
nodeset = new_nodeset
-
-
when :variable
-
var_name = path_stack.shift
-
return @variables[ var_name ]
-
-
# :and, :or, :eq, :neq, :lt, :lteq, :gt, :gteq
-
# TODO: Special case for :or and :and -- not evaluate the right
-
# operand if the left alone determines result (i.e. is true for
-
# :or and false for :and).
-
when :eq, :neq, :lt, :lteq, :gt, :gteq, :or
-
left = expr( path_stack.shift, nodeset.dup, context )
-
#puts "LEFT => #{left.inspect} (#{left.class.name})"
-
right = expr( path_stack.shift, nodeset.dup, context )
-
#puts "RIGHT => #{right.inspect} (#{right.class.name})"
-
res = equality_relational_compare( left, op, right )
-
#puts "RES => #{res.inspect}"
-
return res
-
-
when :and
-
left = expr( path_stack.shift, nodeset.dup, context )
-
#puts "LEFT => #{left.inspect} (#{left.class.name})"
-
return [] unless left
-
if left.respond_to?(:inject) and !left.inject(false) {|a,b| a | b}
-
return []
-
end
-
right = expr( path_stack.shift, nodeset.dup, context )
-
#puts "RIGHT => #{right.inspect} (#{right.class.name})"
-
res = equality_relational_compare( left, op, right )
-
#puts "RES => #{res.inspect}"
-
return res
-
-
when :div
-
left = Functions::number(expr(path_stack.shift, nodeset, context)).to_f
-
right = Functions::number(expr(path_stack.shift, nodeset, context)).to_f
-
return (left / right)
-
-
when :mod
-
left = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
-
right = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
-
return (left % right)
-
-
when :mult
-
left = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
-
right = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
-
return (left * right)
-
-
when :plus
-
left = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
-
right = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
-
return (left + right)
-
-
when :minus
-
left = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
-
right = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
-
return (left - right)
-
-
when :union
-
left = expr( path_stack.shift, nodeset, context )
-
right = expr( path_stack.shift, nodeset, context )
-
return (left | right)
-
-
when :neg
-
res = expr( path_stack, nodeset, context )
-
return -(res.to_f)
-
-
when :not
-
when :function
-
func_name = path_stack.shift.tr('-','_')
-
arguments = path_stack.shift
-
#puts "FUNCTION 0: #{func_name}(#{arguments.collect{|a|a.inspect}.join(', ')})"
-
subcontext = context ? nil : { :size => nodeset.size }
-
-
res = []
-
cont = context
-
nodeset.each_with_index { |n, i|
-
if subcontext
-
subcontext[:node] = n
-
subcontext[:index] = i
-
cont = subcontext
-
end
-
arg_clone = arguments.dclone
-
args = arg_clone.collect { |arg|
-
#puts "FUNCTION 1: Calling expr( #{arg.inspect}, [#{n.inspect}] )"
-
expr( arg, [n], cont )
-
}
-
#puts "FUNCTION 2: #{func_name}(#{args.collect{|a|a.inspect}.join(', ')})"
-
Functions.context = cont
-
res << Functions.send( func_name, *args )
-
#puts "FUNCTION 3: #{res[-1].inspect}"
-
}
-
return res
-
-
end
-
end # while
-
#puts "EXPR returning #{nodeset.inspect}"
-
54
return nodeset
-
end
-
-
-
##########################################################
-
# FIXME
-
# The next two methods are BAD MOJO!
-
# This is my achilles heel. If anybody thinks of a better
-
# way of doing this, be my guest. This really sucks, but
-
# it is a wonder it works at all.
-
# ########################################################
-
-
1
def descendant_or_self( path_stack, nodeset )
-
rs = []
-
#puts "#"*80
-
#puts "PATH_STACK = #{path_stack.inspect}"
-
#puts "NODESET = #{nodeset.collect{|n|n.inspect}.inspect}"
-
d_o_s( path_stack, nodeset, rs )
-
#puts "RS = #{rs.collect{|n|n.inspect}.inspect}"
-
document_order(rs.flatten.compact)
-
#rs.flatten.compact
-
end
-
-
1
def d_o_s( p, ns, r )
-
#puts "IN DOS with #{ns.inspect}; ALREADY HAVE #{r.inspect}"
-
nt = nil
-
ns.each_index do |i|
-
n = ns[i]
-
#puts "P => #{p.inspect}"
-
x = expr( p.dclone, [ n ] )
-
nt = n.node_type
-
d_o_s( p, n.children, x ) if nt == :element or nt == :document and n.children.size > 0
-
r.concat(x) if x.size > 0
-
end
-
end
-
-
-
# Reorders an array of nodes so that they are in document order
-
# It tries to do this efficiently.
-
#
-
# FIXME: I need to get rid of this, but the issue is that most of the XPath
-
# interpreter functions as a filter, which means that we lose context going
-
# in and out of function calls. If I knew what the index of the nodes was,
-
# I wouldn't have to do this. Maybe add a document IDX for each node?
-
# Problems with mutable documents. Or, rewrite everything.
-
1
def document_order( array_of_nodes )
-
new_arry = []
-
array_of_nodes.each { |node|
-
node_idx = []
-
np = node.node_type == :attribute ? node.element : node
-
while np.parent and np.parent.node_type == :element
-
node_idx << np.parent.index( np )
-
np = np.parent
-
end
-
new_arry << [ node_idx.reverse, node ]
-
}
-
#puts "new_arry = #{new_arry.inspect}"
-
new_arry.sort{ |s1, s2| s1[0] <=> s2[0] }.collect{ |s| s[1] }
-
end
-
-
-
1
def recurse( nodeset, &block )
-
for node in nodeset
-
yield node
-
recurse( node, &block ) if node.node_type == :element
-
end
-
end
-
-
-
-
# Builds a nodeset of all of the preceding nodes of the supplied node,
-
# in reverse document order
-
# preceding:: includes every element in the document that precedes this node,
-
# except for ancestors
-
1
def preceding( node )
-
#puts "IN PRECEDING"
-
ancestors = []
-
p = node.parent
-
while p
-
ancestors << p
-
p = p.parent
-
end
-
-
acc = []
-
p = preceding_node_of( node )
-
#puts "P = #{p.inspect}"
-
while p
-
if ancestors.include? p
-
ancestors.delete(p)
-
else
-
acc << p
-
end
-
p = preceding_node_of( p )
-
#puts "P = #{p.inspect}"
-
end
-
acc
-
end
-
-
1
def preceding_node_of( node )
-
#puts "NODE: #{node.inspect}"
-
#puts "PREVIOUS NODE: #{node.previous_sibling_node.inspect}"
-
#puts "PARENT NODE: #{node.parent}"
-
psn = node.previous_sibling_node
-
if psn.nil?
-
if node.parent.nil? or node.parent.class == Document
-
return nil
-
end
-
return node.parent
-
#psn = preceding_node_of( node.parent )
-
end
-
while psn and psn.kind_of? Element and psn.children.size > 0
-
psn = psn.children[-1]
-
end
-
psn
-
end
-
-
1
def following( node )
-
#puts "IN PRECEDING"
-
acc = []
-
p = next_sibling_node( node )
-
#puts "P = #{p.inspect}"
-
while p
-
acc << p
-
p = following_node_of( p )
-
#puts "P = #{p.inspect}"
-
end
-
acc
-
end
-
-
1
def following_node_of( node )
-
#puts "NODE: #{node.inspect}"
-
#puts "PREVIOUS NODE: #{node.previous_sibling_node.inspect}"
-
#puts "PARENT NODE: #{node.parent}"
-
if node.kind_of? Element and node.children.size > 0
-
return node.children[0]
-
end
-
return next_sibling_node(node)
-
end
-
-
1
def next_sibling_node(node)
-
psn = node.next_sibling_node
-
while psn.nil?
-
if node.parent.nil? or node.parent.class == Document
-
return nil
-
end
-
node = node.parent
-
psn = node.next_sibling_node
-
#puts "psn = #{psn.inspect}"
-
end
-
return psn
-
end
-
-
1
def norm b
-
case b
-
when true, false
-
return b
-
when 'true', 'false'
-
return Functions::boolean( b )
-
when /^\d+(\.\d+)?$/
-
return Functions::number( b )
-
else
-
return Functions::string( b )
-
end
-
end
-
-
1
def equality_relational_compare( set1, op, set2 )
-
#puts "EQ_REL_COMP(#{set1.inspect} #{op.inspect} #{set2.inspect})"
-
if set1.kind_of? Array and set2.kind_of? Array
-
#puts "#{set1.size} & #{set2.size}"
-
if set1.size == 1 and set2.size == 1
-
set1 = set1[0]
-
set2 = set2[0]
-
elsif set1.size == 0 or set2.size == 0
-
nd = set1.size==0 ? set2 : set1
-
rv = nd.collect { |il| compare( il, op, nil ) }
-
#puts "RV = #{rv.inspect}"
-
return rv
-
else
-
res = []
-
SyncEnumerator.new( set1, set2 ).each { |i1, i2|
-
#puts "i1 = #{i1.inspect} (#{i1.class.name})"
-
#puts "i2 = #{i2.inspect} (#{i2.class.name})"
-
i1 = norm( i1 )
-
i2 = norm( i2 )
-
res << compare( i1, op, i2 )
-
}
-
return res
-
end
-
end
-
#puts "EQ_REL_COMP: #{set1.inspect} (#{set1.class.name}), #{op}, #{set2.inspect} (#{set2.class.name})"
-
#puts "COMPARING VALUES"
-
# If one is nodeset and other is number, compare number to each item
-
# in nodeset s.t. number op number(string(item))
-
# If one is nodeset and other is string, compare string to each item
-
# in nodeset s.t. string op string(item)
-
# If one is nodeset and other is boolean, compare boolean to each item
-
# in nodeset s.t. boolean op boolean(item)
-
if set1.kind_of? Array or set2.kind_of? Array
-
#puts "ISA ARRAY"
-
if set1.kind_of? Array
-
a = set1
-
b = set2
-
else
-
a = set2
-
b = set1
-
end
-
-
case b
-
when true, false
-
return a.collect {|v| compare( Functions::boolean(v), op, b ) }
-
when Numeric
-
return a.collect {|v| compare( Functions::number(v), op, b )}
-
when /^\d+(\.\d+)?$/
-
b = Functions::number( b )
-
#puts "B = #{b.inspect}"
-
return a.collect {|v| compare( Functions::number(v), op, b )}
-
else
-
#puts "Functions::string( #{b}(#{b.class.name}) ) = #{Functions::string(b)}"
-
b = Functions::string( b )
-
return a.collect { |v| compare( Functions::string(v), op, b ) }
-
end
-
else
-
# If neither is nodeset,
-
# If op is = or !=
-
# If either boolean, convert to boolean
-
# If either number, convert to number
-
# Else, convert to string
-
# Else
-
# Convert both to numbers and compare
-
s1 = set1.to_s
-
s2 = set2.to_s
-
#puts "EQ_REL_COMP: #{set1}=>#{s1}, #{set2}=>#{s2}"
-
if s1 == 'true' or s1 == 'false' or s2 == 'true' or s2 == 'false'
-
#puts "Functions::boolean(#{set1})=>#{Functions::boolean(set1)}"
-
#puts "Functions::boolean(#{set2})=>#{Functions::boolean(set2)}"
-
set1 = Functions::boolean( set1 )
-
set2 = Functions::boolean( set2 )
-
else
-
if op == :eq or op == :neq
-
if s1 =~ /^\d+(\.\d+)?$/ or s2 =~ /^\d+(\.\d+)?$/
-
set1 = Functions::number( s1 )
-
set2 = Functions::number( s2 )
-
else
-
set1 = Functions::string( set1 )
-
set2 = Functions::string( set2 )
-
end
-
else
-
set1 = Functions::number( set1 )
-
set2 = Functions::number( set2 )
-
end
-
end
-
#puts "EQ_REL_COMP: #{set1} #{op} #{set2}"
-
#puts ">>> #{compare( set1, op, set2 )}"
-
return compare( set1, op, set2 )
-
end
-
return false
-
end
-
-
1
def compare a, op, b
-
#puts "COMPARE #{a.inspect}(#{a.class.name}) #{op} #{b.inspect}(#{b.class.name})"
-
case op
-
when :eq
-
a == b
-
when :neq
-
a != b
-
when :lt
-
a < b
-
when :lteq
-
a <= b
-
when :gt
-
a > b
-
when :gteq
-
a >= b
-
when :and
-
a and b
-
when :or
-
a or b
-
else
-
false
-
end
-
end
-
end
-
end
-
# Copyright (c) 2003, 2004 Jim Weirich, 2009 Eric Hodel
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-
1
require 'rubygems'
-
1
begin
-
1
gem 'rake'
-
rescue Gem::LoadError
-
end
-
-
1
require 'rake/packagetask'
-
-
##
-
# Create a package based upon a Gem::Specification. Gem packages, as well as
-
# zip files and tar/gzipped packages can be produced by this task.
-
#
-
# In addition to the Rake targets generated by Rake::PackageTask, a
-
# Gem::PackageTask will also generate the following tasks:
-
#
-
# [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.gem"</b>]
-
# Create a RubyGems package with the given name and version.
-
#
-
# Example using a Gem::Specification:
-
#
-
# require 'rubygems'
-
# require 'rubygems/package_task'
-
#
-
# spec = Gem::Specification.new do |s|
-
# s.platform = Gem::Platform::RUBY
-
# s.summary = "Ruby based make-like utility."
-
# s.name = 'rake'
-
# s.version = PKG_VERSION
-
# s.requirements << 'none'
-
# s.require_path = 'lib'
-
# s.autorequire = 'rake'
-
# s.files = PKG_FILES
-
# s.description = <<-EOF
-
# Rake is a Make-like program implemented in Ruby. Tasks
-
# and dependencies are specified in standard Ruby syntax.
-
# EOF
-
# end
-
#
-
# Gem::PackageTask.new(spec) do |pkg|
-
# pkg.need_zip = true
-
# pkg.need_tar = true
-
# end
-
-
1
class Gem::PackageTask < Rake::PackageTask
-
-
##
-
# Ruby Gem::Specification containing the metadata for this package. The
-
# name, version and package_files are automatically determined from the
-
# gemspec and don't need to be explicitly provided.
-
-
1
attr_accessor :gem_spec
-
-
##
-
# Create a Gem Package task library. Automatically define the gem if a
-
# block is given. If no block is supplied, then #define needs to be called
-
# to define the task.
-
-
1
def initialize(gem_spec)
-
1
init gem_spec
-
1
yield self if block_given?
-
1
define if block_given?
-
end
-
-
##
-
# Initialization tasks without the "yield self" or define operations.
-
-
1
def init(gem)
-
1
super gem.full_name, :noversion
-
1
@gem_spec = gem
-
1
@package_files += gem_spec.files if gem_spec.files
-
end
-
-
##
-
# Create the Rake tasks and actions specified by this Gem::PackageTask.
-
# (+define+ is automatically called if a block is given to +new+).
-
-
1
def define
-
1
super
-
-
1
task :package => [:gem]
-
-
1
gem_file = File.basename gem_spec.cache_file
-
1
gem_path = File.join package_dir, gem_file
-
1
gem_dir = File.join package_dir, gem_spec.full_name
-
-
1
desc "Build the gem file #{gem_file}"
-
1
task :gem => [gem_path]
-
-
1
trace = Rake.application.options.trace
-
1
Gem.configuration.verbose = trace
-
-
1
file gem_path => [package_dir, gem_dir] + @gem_spec.files do
-
chdir(gem_dir) do
-
when_writing "Creating #{gem_spec.file_name}" do
-
Gem::Builder.new(gem_spec).build
-
verbose trace do
-
mv gem_file, '..'
-
end
-
end
-
end
-
end
-
end
-
-
end
-
-
# = Secure random number generator interface.
-
#
-
# This library is an interface for secure random number generator which is
-
# suitable for generating session key in HTTP cookies, etc.
-
#
-
# It supports following secure random number generators.
-
#
-
# * openssl
-
# * /dev/urandom
-
# * Win32
-
#
-
# == Example
-
#
-
# # random hexadecimal string.
-
# p SecureRandom.hex(10) #=> "52750b30ffbc7de3b362"
-
# p SecureRandom.hex(10) #=> "92b15d6c8dc4beb5f559"
-
# p SecureRandom.hex(11) #=> "6aca1b5c58e4863e6b81b8"
-
# p SecureRandom.hex(12) #=> "94b2fff3e7fd9b9c391a2306"
-
# p SecureRandom.hex(13) #=> "39b290146bea6ce975c37cfc23"
-
# ...
-
#
-
# # random base64 string.
-
# p SecureRandom.base64(10) #=> "EcmTPZwWRAozdA=="
-
# p SecureRandom.base64(10) #=> "9b0nsevdwNuM/w=="
-
# p SecureRandom.base64(10) #=> "KO1nIU+p9DKxGg=="
-
# p SecureRandom.base64(11) #=> "l7XEiFja+8EKEtY="
-
# p SecureRandom.base64(12) #=> "7kJSM/MzBJI+75j8"
-
# p SecureRandom.base64(13) #=> "vKLJ0tXBHqQOuIcSIg=="
-
# ...
-
#
-
# # random binary string.
-
# p SecureRandom.random_bytes(10) #=> "\016\t{\370g\310pbr\301"
-
# p SecureRandom.random_bytes(10) #=> "\323U\030TO\234\357\020\a\337"
-
# ...
-
-
1
begin
-
1
require 'openssl'
-
rescue LoadError
-
end
-
-
1
module SecureRandom
-
# SecureRandom.random_bytes generates a random binary string.
-
#
-
# The argument _n_ specifies the length of the result string.
-
#
-
# If _n_ is not specified, 16 is assumed.
-
# It may be larger in future.
-
#
-
# The result may contain any byte: "\x00" - "\xff".
-
#
-
# p SecureRandom.random_bytes #=> "\xD8\\\xE0\xF4\r\xB2\xFC*WM\xFF\x83\x18\xF45\xB6"
-
# p SecureRandom.random_bytes #=> "m\xDC\xFC/\a\x00Uf\xB2\xB2P\xBD\xFF6S\x97"
-
#
-
# If secure random number generator is not available,
-
# NotImplementedError is raised.
-
1
def self.random_bytes(n=nil)
-
22
n ||= 16
-
-
22
if defined? OpenSSL::Random
-
22
@pid = 0 if !defined?(@pid)
-
22
pid = $$
-
22
if @pid != pid
-
1
now = Time.now
-
1
ary = [now.to_i, now.nsec, @pid, pid]
-
1
OpenSSL::Random.seed(ary.to_s)
-
1
@pid = pid
-
end
-
22
return OpenSSL::Random.random_bytes(n)
-
end
-
-
if !defined?(@has_urandom) || @has_urandom
-
flags = File::RDONLY
-
flags |= File::NONBLOCK if defined? File::NONBLOCK
-
flags |= File::NOCTTY if defined? File::NOCTTY
-
begin
-
File.open("/dev/urandom", flags) {|f|
-
unless f.stat.chardev?
-
raise Errno::ENOENT
-
end
-
@has_urandom = true
-
ret = f.readpartial(n)
-
if ret.length != n
-
raise NotImplementedError, "Unexpected partial read from random device"
-
end
-
return ret
-
}
-
rescue Errno::ENOENT
-
@has_urandom = false
-
end
-
end
-
-
if !defined?(@has_win32)
-
begin
-
require 'Win32API'
-
-
crypt_acquire_context = Win32API.new("advapi32", "CryptAcquireContext", 'PPPII', 'L')
-
@crypt_gen_random = Win32API.new("advapi32", "CryptGenRandom", 'LIP', 'L')
-
-
hProvStr = " " * 4
-
prov_rsa_full = 1
-
crypt_verifycontext = 0xF0000000
-
-
if crypt_acquire_context.call(hProvStr, nil, nil, prov_rsa_full, crypt_verifycontext) == 0
-
raise SystemCallError, "CryptAcquireContext failed: #{lastWin32ErrorMessage}"
-
end
-
@hProv, = hProvStr.unpack('L')
-
-
@has_win32 = true
-
rescue LoadError
-
@has_win32 = false
-
end
-
end
-
if @has_win32
-
bytes = " ".force_encoding("ASCII-8BIT") * n
-
if @crypt_gen_random.call(@hProv, bytes.size, bytes) == 0
-
raise SystemCallError, "CryptGenRandom failed: #{lastWin32ErrorMessage}"
-
end
-
return bytes
-
end
-
-
raise NotImplementedError, "No random device"
-
end
-
-
# SecureRandom.hex generates a random hex string.
-
#
-
# The argument _n_ specifies the length of the random length.
-
# The length of the result string is twice of _n_.
-
#
-
# If _n_ is not specified, 16 is assumed.
-
# It may be larger in future.
-
#
-
# The result may contain 0-9 and a-f.
-
#
-
# p SecureRandom.hex #=> "eb693ec8252cd630102fd0d0fb7c3485"
-
# p SecureRandom.hex #=> "91dc3bfb4de5b11d029d376634589b61"
-
#
-
# If secure random number generator is not available,
-
# NotImplementedError is raised.
-
1
def self.hex(n=nil)
-
22
random_bytes(n).unpack("H*")[0]
-
end
-
-
# SecureRandom.base64 generates a random base64 string.
-
#
-
# The argument _n_ specifies the length of the random length.
-
# The length of the result string is about 4/3 of _n_.
-
#
-
# If _n_ is not specified, 16 is assumed.
-
# It may be larger in future.
-
#
-
# The result may contain A-Z, a-z, 0-9, "+", "/" and "=".
-
#
-
# p SecureRandom.base64 #=> "/2BuBuLf3+WfSKyQbRcc/A=="
-
# p SecureRandom.base64 #=> "6BbW0pxO0YENxn38HMUbcQ=="
-
#
-
# If secure random number generator is not available,
-
# NotImplementedError is raised.
-
#
-
# See RFC 3548 for the definition of base64.
-
1
def self.base64(n=nil)
-
[random_bytes(n)].pack("m*").delete("\n")
-
end
-
-
# SecureRandom.urlsafe_base64 generates a random URL-safe base64 string.
-
#
-
# The argument _n_ specifies the length of the random length.
-
# The length of the result string is about 4/3 of _n_.
-
#
-
# If _n_ is not specified, 16 is assumed.
-
# It may be larger in future.
-
#
-
# The boolean argument _padding_ specifies the padding.
-
# If it is false or nil, padding is not generated.
-
# Otherwise padding is generated.
-
# By default, padding is not generated because "=" may be used as a URL delimiter.
-
#
-
# The result may contain A-Z, a-z, 0-9, "-" and "_".
-
# "=" is also used if _padding_ is true.
-
#
-
# p SecureRandom.urlsafe_base64 #=> "b4GOKm4pOYU_-BOXcrUGDg"
-
# p SecureRandom.urlsafe_base64 #=> "UZLdOkzop70Ddx-IJR0ABg"
-
#
-
# p SecureRandom.urlsafe_base64(nil, true) #=> "i0XQ-7gglIsHGV2_BNPrdQ=="
-
# p SecureRandom.urlsafe_base64(nil, true) #=> "-M8rLhr7JEpJlqFGUMmOxg=="
-
#
-
# If secure random number generator is not available,
-
# NotImplementedError is raised.
-
#
-
# See RFC 3548 for the definition of URL-safe base64.
-
1
def self.urlsafe_base64(n=nil, padding=false)
-
s = [random_bytes(n)].pack("m*")
-
s.delete!("\n")
-
s.tr!("+/", "-_")
-
s.delete!("=") if !padding
-
s
-
end
-
-
# SecureRandom.random_number generates a random number.
-
#
-
# If a positive integer is given as _n_,
-
# SecureRandom.random_number returns an integer:
-
# 0 <= SecureRandom.random_number(n) < n.
-
#
-
# p SecureRandom.random_number(100) #=> 15
-
# p SecureRandom.random_number(100) #=> 88
-
#
-
# If 0 is given or an argument is not given,
-
# SecureRandom.random_number returns a float:
-
# 0.0 <= SecureRandom.random_number() < 1.0.
-
#
-
# p SecureRandom.random_number #=> 0.596506046187744
-
# p SecureRandom.random_number #=> 0.350621695741409
-
#
-
1
def self.random_number(n=0)
-
if 0 < n
-
hex = n.to_s(16)
-
hex = '0' + hex if (hex.length & 1) == 1
-
bin = [hex].pack("H*")
-
mask = bin[0].ord
-
mask |= mask >> 1
-
mask |= mask >> 2
-
mask |= mask >> 4
-
begin
-
rnd = SecureRandom.random_bytes(bin.length)
-
rnd[0] = (rnd[0].ord & mask).chr
-
end until rnd < bin
-
rnd.unpack("H*")[0].hex
-
else
-
# assumption: Float::MANT_DIG <= 64
-
i64 = SecureRandom.random_bytes(8).unpack("Q")[0]
-
Math.ldexp(i64 >> (64-Float::MANT_DIG), -Float::MANT_DIG)
-
end
-
end
-
-
# SecureRandom.uuid generates a v4 random UUID (Universally Unique IDentifier).
-
#
-
# p SecureRandom.uuid #=> "2d931510-d99f-494a-8c67-87feb05e1594"
-
# p SecureRandom.uuid #=> "bad85eb9-0713-4da7-8d36-07a8e4b00eab"
-
# p SecureRandom.uuid #=> "62936e70-1815-439b-bf89-8492855a7e6b"
-
#
-
# The version 4 UUID is purely random (except the version).
-
# It doesn't contain meaningful information such as MAC address, time, etc.
-
#
-
# See RFC 4122 for details of UUID.
-
#
-
1
def self.uuid
-
ary = self.random_bytes(16).unpack("NnnnnN")
-
ary[2] = (ary[2] & 0x0fff) | 0x4000
-
ary[3] = (ary[3] & 0x3fff) | 0x8000
-
"%08x-%04x-%04x-%04x-%04x%08x" % ary
-
end
-
-
# Following code is based on David Garamond's GUID library for Ruby.
-
1
def self.lastWin32ErrorMessage # :nodoc:
-
get_last_error = Win32API.new("kernel32", "GetLastError", '', 'L')
-
format_message = Win32API.new("kernel32", "FormatMessageA", 'LPLLPLPPPPPPPP', 'L')
-
format_message_ignore_inserts = 0x00000200
-
format_message_from_system = 0x00001000
-
-
code = get_last_error.call
-
msg = "\0" * 1024
-
len = format_message.call(format_message_ignore_inserts + format_message_from_system, 0, code, 0, msg, 1024, nil, nil, nil, nil, nil, nil, nil, nil)
-
msg[0, len].tr("\r", '').chomp
-
end
-
end
-
1
require 'socket.so'
-
-
1
class Addrinfo
-
# creates an Addrinfo object from the arguments.
-
#
-
# The arguments are interpreted as similar to self.
-
#
-
# Addrinfo.tcp("0.0.0.0", 4649).family_addrinfo("www.ruby-lang.org", 80)
-
# #=> #<Addrinfo: 221.186.184.68:80 TCP (www.ruby-lang.org:80)>
-
#
-
# Addrinfo.unix("/tmp/sock").family_addrinfo("/tmp/sock2")
-
# #=> #<Addrinfo: /tmp/sock2 SOCK_STREAM>
-
#
-
1
def family_addrinfo(*args)
-
if args.empty?
-
raise ArgumentError, "no address specified"
-
elsif Addrinfo === args.first
-
raise ArgumentError, "too many arguments" if args.length != 1
-
elsif self.ip?
-
raise ArgumentError, "IP address needs host and port but #{args.length} arguments given" if args.length != 2
-
host, port = args
-
Addrinfo.getaddrinfo(host, port, self.pfamily, self.socktype, self.protocol)[0]
-
elsif self.unix?
-
raise ArgumentError, "UNIX socket needs single path argument but #{args.length} arguments given" if args.length != 1
-
path, = args
-
Addrinfo.unix(path)
-
else
-
raise ArgumentError, "unexpected family"
-
end
-
end
-
-
# creates a new Socket connected to the address of +local_addrinfo+.
-
#
-
# If no arguments are given, the address of the socket is not bound.
-
#
-
# If a block is given the created socket is yielded for each address.
-
#
-
1
def connect_internal(local_addrinfo) # :yields: socket
-
sock = Socket.new(self.pfamily, self.socktype, self.protocol)
-
begin
-
sock.ipv6only! if self.ipv6?
-
sock.bind local_addrinfo if local_addrinfo
-
sock.connect(self)
-
if block_given?
-
yield sock
-
else
-
sock
-
end
-
ensure
-
sock.close if !sock.closed? && (block_given? || $!)
-
end
-
end
-
1
private :connect_internal
-
-
# creates a socket connected to the address of self.
-
#
-
# If one or more arguments given as _local_addr_args_,
-
# it is used as the local address of the socket.
-
# _local_addr_args_ is given for family_addrinfo to obtain actual address.
-
#
-
# If no arguments given, the local address of the socket is not bound.
-
#
-
# If a block is given, it is called with the socket and the value of the block is returned.
-
# The socket is returned otherwise.
-
#
-
# Addrinfo.tcp("www.ruby-lang.org", 80).connect_from("0.0.0.0", 4649) {|s|
-
# s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
-
# puts s.read
-
# }
-
#
-
# # Addrinfo object can be taken for the argument.
-
# Addrinfo.tcp("www.ruby-lang.org", 80).connect_from(Addrinfo.tcp("0.0.0.0", 4649)) {|s|
-
# s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
-
# puts s.read
-
# }
-
#
-
1
def connect_from(*local_addr_args, &block)
-
connect_internal(family_addrinfo(*local_addr_args), &block)
-
end
-
-
# creates a socket connected to the address of self.
-
#
-
# If a block is given, it is called with the socket and the value of the block is returned.
-
# The socket is returned otherwise.
-
#
-
# Addrinfo.tcp("www.ruby-lang.org", 80).connect {|s|
-
# s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
-
# puts s.read
-
# }
-
#
-
1
def connect(&block)
-
connect_internal(nil, &block)
-
end
-
-
# creates a socket connected to _remote_addr_args_ and bound to self.
-
#
-
# If a block is given, it is called with the socket and the value of the block is returned.
-
# The socket is returned otherwise.
-
#
-
# Addrinfo.tcp("0.0.0.0", 4649).connect_to("www.ruby-lang.org", 80) {|s|
-
# s.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
-
# puts s.read
-
# }
-
#
-
1
def connect_to(*remote_addr_args, &block)
-
remote_addrinfo = family_addrinfo(*remote_addr_args)
-
remote_addrinfo.send(:connect_internal, self, &block)
-
end
-
-
# creates a socket bound to self.
-
#
-
# If a block is given, it is called with the socket and the value of the block is returned.
-
# The socket is returned otherwise.
-
#
-
# Addrinfo.udp("0.0.0.0", 9981).bind {|s|
-
# s.local_address.connect {|s| s.send "hello", 0 }
-
# p s.recv(10) #=> "hello"
-
# }
-
#
-
1
def bind
-
sock = Socket.new(self.pfamily, self.socktype, self.protocol)
-
begin
-
sock.ipv6only! if self.ipv6?
-
sock.setsockopt(:SOCKET, :REUSEADDR, 1)
-
sock.bind(self)
-
if block_given?
-
yield sock
-
else
-
sock
-
end
-
ensure
-
sock.close if !sock.closed? && (block_given? || $!)
-
end
-
end
-
-
# creates a listening socket bound to self.
-
1
def listen(backlog=5)
-
sock = Socket.new(self.pfamily, self.socktype, self.protocol)
-
begin
-
sock.ipv6only! if self.ipv6?
-
sock.setsockopt(:SOCKET, :REUSEADDR, 1)
-
sock.bind(self)
-
sock.listen(backlog)
-
if block_given?
-
yield sock
-
else
-
sock
-
end
-
ensure
-
sock.close if !sock.closed? && (block_given? || $!)
-
end
-
end
-
-
# iterates over the list of Addrinfo objects obtained by Addrinfo.getaddrinfo.
-
#
-
# Addrinfo.foreach(nil, 80) {|x| p x }
-
# #=> #<Addrinfo: 127.0.0.1:80 TCP (:80)>
-
# # #<Addrinfo: 127.0.0.1:80 UDP (:80)>
-
# # #<Addrinfo: [::1]:80 TCP (:80)>
-
# # #<Addrinfo: [::1]:80 UDP (:80)>
-
#
-
1
def self.foreach(nodename, service, family=nil, socktype=nil, protocol=nil, flags=nil, &block)
-
Addrinfo.getaddrinfo(nodename, service, family, socktype, protocol, flags).each(&block)
-
end
-
end
-
-
1
class BasicSocket < IO
-
# Returns an address of the socket suitable for connect in the local machine.
-
#
-
# This method returns _self_.local_address, except following condition.
-
#
-
# - IPv4 unspecified address (0.0.0.0) is replaced by IPv4 loopback address (127.0.0.1).
-
# - IPv6 unspecified address (::) is replaced by IPv6 loopback address (::1).
-
#
-
# If the local address is not suitable for connect, SocketError is raised.
-
# IPv4 and IPv6 address which port is 0 is not suitable for connect.
-
# Unix domain socket which has no path is not suitable for connect.
-
#
-
# Addrinfo.tcp("0.0.0.0", 0).listen {|serv|
-
# p serv.connect_address #=> #<Addrinfo: 127.0.0.1:53660 TCP>
-
# serv.connect_address.connect {|c|
-
# s, _ = serv.accept
-
# p [c, s] #=> [#<Socket:fd 4>, #<Socket:fd 6>]
-
# }
-
# }
-
#
-
1
def connect_address
-
addr = local_address
-
afamily = addr.afamily
-
if afamily == Socket::AF_INET
-
raise SocketError, "unbound IPv4 socket" if addr.ip_port == 0
-
if addr.ip_address == "0.0.0.0"
-
addr = Addrinfo.new(["AF_INET", addr.ip_port, nil, "127.0.0.1"], addr.pfamily, addr.socktype, addr.protocol)
-
end
-
elsif defined?(Socket::AF_INET6) && afamily == Socket::AF_INET6
-
raise SocketError, "unbound IPv6 socket" if addr.ip_port == 0
-
if addr.ip_address == "::"
-
addr = Addrinfo.new(["AF_INET6", addr.ip_port, nil, "::1"], addr.pfamily, addr.socktype, addr.protocol)
-
elsif addr.ip_address == "0.0.0.0" # MacOS X 10.4 returns "a.b.c.d" for IPv4-mapped IPv6 address.
-
addr = Addrinfo.new(["AF_INET6", addr.ip_port, nil, "::1"], addr.pfamily, addr.socktype, addr.protocol)
-
elsif addr.ip_address == "::ffff:0.0.0.0" # MacOS X 10.6 returns "::ffff:a.b.c.d" for IPv4-mapped IPv6 address.
-
addr = Addrinfo.new(["AF_INET6", addr.ip_port, nil, "::1"], addr.pfamily, addr.socktype, addr.protocol)
-
end
-
elsif defined?(Socket::AF_UNIX) && afamily == Socket::AF_UNIX
-
raise SocketError, "unbound Unix socket" if addr.unix_path == ""
-
end
-
addr
-
end
-
end
-
-
1
class Socket < BasicSocket
-
# enable the socket option IPV6_V6ONLY if IPV6_V6ONLY is available.
-
1
def ipv6only!
-
if defined? Socket::IPV6_V6ONLY
-
self.setsockopt(:IPV6, :V6ONLY, 1)
-
end
-
end
-
-
# creates a new socket object connected to host:port using TCP/IP.
-
#
-
# If local_host:local_port is given,
-
# the socket is bound to it.
-
#
-
# If a block is given, the block is called with the socket.
-
# The value of the block is returned.
-
# The socket is closed when this method returns.
-
#
-
# If no block is given, the socket is returned.
-
#
-
# Socket.tcp("www.ruby-lang.org", 80) {|sock|
-
# sock.print "GET / HTTP/1.0\r\nHost: www.ruby-lang.org\r\n\r\n"
-
# sock.close_write
-
# puts sock.read
-
# }
-
#
-
1
def self.tcp(host, port, local_host=nil, local_port=nil) # :yield: socket
-
last_error = nil
-
ret = nil
-
-
local_addr_list = nil
-
if local_host != nil || local_port != nil
-
local_addr_list = Addrinfo.getaddrinfo(local_host, local_port, nil, :STREAM, nil)
-
end
-
-
Addrinfo.foreach(host, port, nil, :STREAM) {|ai|
-
if local_addr_list
-
local_addr = local_addr_list.find {|local_ai| local_ai.afamily == ai.afamily }
-
next if !local_addr
-
else
-
local_addr = nil
-
end
-
begin
-
sock = local_addr ? ai.connect_from(local_addr) : ai.connect
-
rescue SystemCallError
-
last_error = $!
-
next
-
end
-
ret = sock
-
break
-
}
-
if !ret
-
if last_error
-
raise last_error
-
else
-
raise SocketError, "no appropriate local address"
-
end
-
end
-
if block_given?
-
begin
-
yield ret
-
ensure
-
ret.close if !ret.closed?
-
end
-
else
-
ret
-
end
-
end
-
-
# :stopdoc:
-
1
def self.ip_sockets_port0(ai_list, reuseaddr)
-
begin
-
sockets = []
-
port = nil
-
ai_list.each {|ai|
-
begin
-
s = Socket.new(ai.pfamily, ai.socktype, ai.protocol)
-
rescue SystemCallError
-
next
-
end
-
sockets << s
-
s.ipv6only! if ai.ipv6?
-
if reuseaddr
-
s.setsockopt(:SOCKET, :REUSEADDR, 1)
-
end
-
if !port
-
s.bind(ai)
-
port = s.local_address.ip_port
-
else
-
s.bind(ai.family_addrinfo(ai.ip_address, port))
-
end
-
}
-
rescue Errno::EADDRINUSE
-
sockets.each {|s|
-
s.close
-
}
-
retry
-
end
-
sockets
-
ensure
-
sockets.each {|s| s.close if !s.closed? } if $!
-
end
-
1
class << self
-
1
private :ip_sockets_port0
-
end
-
-
1
def self.tcp_server_sockets_port0(host)
-
ai_list = Addrinfo.getaddrinfo(host, 0, nil, :STREAM, nil, Socket::AI_PASSIVE)
-
sockets = ip_sockets_port0(ai_list, true)
-
sockets.each {|s|
-
s.listen(5)
-
}
-
sockets
-
ensure
-
sockets.each {|s| s.close if !s.closed? } if $! && sockets
-
end
-
1
class << self
-
1
private :tcp_server_sockets_port0
-
end
-
# :startdoc:
-
-
# creates TCP/IP server sockets for _host_ and _port_.
-
# _host_ is optional.
-
#
-
# If no block given,
-
# it returns an array of listening sockets.
-
#
-
# If a block is given, the block is called with the sockets.
-
# The value of the block is returned.
-
# The socket is closed when this method returns.
-
#
-
# If _port_ is 0, actual port number is choosen dynamically.
-
# However all sockets in the result has same port number.
-
#
-
# # tcp_server_sockets returns two sockets.
-
# sockets = Socket.tcp_server_sockets(1296)
-
# p sockets #=> [#<Socket:fd 3>, #<Socket:fd 4>]
-
#
-
# # The sockets contains IPv6 and IPv4 sockets.
-
# sockets.each {|s| p s.local_address }
-
# #=> #<Addrinfo: [::]:1296 TCP>
-
# # #<Addrinfo: 0.0.0.0:1296 TCP>
-
#
-
# # IPv6 and IPv4 socket has same port number, 53114, even if it is choosen dynamically.
-
# sockets = Socket.tcp_server_sockets(0)
-
# sockets.each {|s| p s.local_address }
-
# #=> #<Addrinfo: [::]:53114 TCP>
-
# # #<Addrinfo: 0.0.0.0:53114 TCP>
-
#
-
# # The block is called with the sockets.
-
# Socket.tcp_server_sockets(0) {|sockets|
-
# p sockets #=> [#<Socket:fd 3>, #<Socket:fd 4>]
-
# }
-
#
-
1
def self.tcp_server_sockets(host=nil, port)
-
if port == 0
-
sockets = tcp_server_sockets_port0(host)
-
else
-
begin
-
last_error = nil
-
sockets = []
-
Addrinfo.foreach(host, port, nil, :STREAM, nil, Socket::AI_PASSIVE) {|ai|
-
begin
-
s = ai.listen
-
rescue SystemCallError
-
last_error = $!
-
next
-
end
-
sockets << s
-
}
-
if sockets.empty?
-
raise last_error
-
end
-
ensure
-
sockets.each {|s| s.close if !s.closed? } if $!
-
end
-
end
-
if block_given?
-
begin
-
yield sockets
-
ensure
-
sockets.each {|s| s.close if !s.closed? }
-
end
-
else
-
sockets
-
end
-
end
-
-
# yield socket and client address for each a connection accepted via given sockets.
-
#
-
# The arguments are a list of sockets.
-
# The individual argument should be a socket or an array of sockets.
-
#
-
# This method yields the block sequentially.
-
# It means that the next connection is not accepted until the block returns.
-
# So concurrent mechanism, thread for example, should be used to service multiple clients at a time.
-
#
-
1
def self.accept_loop(*sockets) # :yield: socket, client_addrinfo
-
sockets.flatten!(1)
-
if sockets.empty?
-
raise ArgumentError, "no sockets"
-
end
-
loop {
-
readable, _, _ = IO.select(sockets)
-
readable.each {|r|
-
begin
-
sock, addr = r.accept_nonblock
-
rescue IO::WaitReadable
-
next
-
end
-
yield sock, addr
-
}
-
}
-
end
-
-
# creates a TCP/IP server on _port_ and calls the block for each connection accepted.
-
# The block is called with a socket and a client_address as an Addrinfo object.
-
#
-
# If _host_ is specified, it is used with _port_ to determine the server addresses.
-
#
-
# The socket is *not* closed when the block returns.
-
# So application should close it explicitly.
-
#
-
# This method calls the block sequentially.
-
# It means that the next connection is not accepted until the block returns.
-
# So concurrent mechanism, thread for example, should be used to service multiple clients at a time.
-
#
-
# Note that Addrinfo.getaddrinfo is used to determine the server socket addresses.
-
# When Addrinfo.getaddrinfo returns two or more addresses,
-
# IPv4 and IPv6 address for example,
-
# all of them are used.
-
# Socket.tcp_server_loop succeeds if one socket can be used at least.
-
#
-
# # Sequential echo server.
-
# # It services only one client at a time.
-
# Socket.tcp_server_loop(16807) {|sock, client_addrinfo|
-
# begin
-
# IO.copy_stream(sock, sock)
-
# ensure
-
# sock.close
-
# end
-
# }
-
#
-
# # Threaded echo server
-
# # It services multiple clients at a time.
-
# # Note that it may accept connections too much.
-
# Socket.tcp_server_loop(16807) {|sock, client_addrinfo|
-
# Thread.new {
-
# begin
-
# IO.copy_stream(sock, sock)
-
# ensure
-
# sock.close
-
# end
-
# }
-
# }
-
#
-
1
def self.tcp_server_loop(host=nil, port, &b) # :yield: socket, client_addrinfo
-
tcp_server_sockets(host, port) {|sockets|
-
accept_loop(sockets, &b)
-
}
-
end
-
-
# :call-seq:
-
# Socket.udp_server_sockets([host, ] port)
-
#
-
# Creates UDP/IP sockets for a UDP server.
-
#
-
# If no block given, it returns an array of sockets.
-
#
-
# If a block is given, the block is called with the sockets.
-
# The value of the block is returned.
-
# The sockets are closed when this method returns.
-
#
-
# If _port_ is zero, some port is choosen.
-
# But the choosen port is used for the all sockets.
-
#
-
# # UDP/IP echo server
-
# Socket.udp_server_sockets(0) {|sockets|
-
# p sockets.first.local_address.ip_port #=> 32963
-
# Socket.udp_server_loop_on(sockets) {|msg, msg_src|
-
# msg_src.reply msg
-
# }
-
# }
-
#
-
1
def self.udp_server_sockets(host=nil, port)
-
last_error = nil
-
sockets = []
-
-
ipv6_recvpktinfo = nil
-
if defined? Socket::AncillaryData
-
if defined? Socket::IPV6_RECVPKTINFO # RFC 3542
-
ipv6_recvpktinfo = Socket::IPV6_RECVPKTINFO
-
elsif defined? Socket::IPV6_PKTINFO # RFC 2292
-
ipv6_recvpktinfo = Socket::IPV6_PKTINFO
-
end
-
end
-
-
local_addrs = Socket.ip_address_list
-
-
ip_list = []
-
Addrinfo.foreach(host, port, nil, :DGRAM, nil, Socket::AI_PASSIVE) {|ai|
-
if ai.ipv4? && ai.ip_address == "0.0.0.0"
-
local_addrs.each {|a|
-
next if !a.ipv4?
-
ip_list << Addrinfo.new(a.to_sockaddr, :INET, :DGRAM, 0);
-
}
-
elsif ai.ipv6? && ai.ip_address == "::" && !ipv6_recvpktinfo
-
local_addrs.each {|a|
-
next if !a.ipv6?
-
ip_list << Addrinfo.new(a.to_sockaddr, :INET6, :DGRAM, 0);
-
}
-
else
-
ip_list << ai
-
end
-
}
-
-
if port == 0
-
sockets = ip_sockets_port0(ip_list, false)
-
else
-
ip_list.each {|ip|
-
ai = Addrinfo.udp(ip.ip_address, port)
-
begin
-
s = ai.bind
-
rescue SystemCallError
-
last_error = $!
-
next
-
end
-
sockets << s
-
}
-
if sockets.empty?
-
raise last_error
-
end
-
end
-
-
sockets.each {|s|
-
ai = s.local_address
-
if ipv6_recvpktinfo && ai.ipv6? && ai.ip_address == "::"
-
s.setsockopt(:IPV6, ipv6_recvpktinfo, 1)
-
end
-
}
-
-
if block_given?
-
begin
-
yield sockets
-
ensure
-
sockets.each {|s| s.close if !s.closed? } if sockets
-
end
-
else
-
sockets
-
end
-
end
-
-
# :call-seq:
-
# Socket.udp_server_recv(sockets) {|msg, msg_src| ... }
-
#
-
# Receive UDP/IP packets from the given _sockets_.
-
# For each packet received, the block is called.
-
#
-
# The block receives _msg_ and _msg_src_.
-
# _msg_ is a string which is the payload of the received packet.
-
# _msg_src_ is a Socket::UDPSource object which is used for reply.
-
#
-
# Socket.udp_server_loop can be implemented using this method as follows.
-
#
-
# udp_server_sockets(host, port) {|sockets|
-
# loop {
-
# readable, _, _ = IO.select(sockets)
-
# udp_server_recv(readable) {|msg, msg_src| ... }
-
# }
-
# }
-
#
-
1
def self.udp_server_recv(sockets)
-
sockets.each {|r|
-
begin
-
msg, sender_addrinfo, _, *controls = r.recvmsg_nonblock
-
rescue IO::WaitReadable
-
next
-
end
-
ai = r.local_address
-
if ai.ipv6? and pktinfo = controls.find {|c| c.cmsg_is?(:IPV6, :PKTINFO) }
-
ai = Addrinfo.udp(pktinfo.ipv6_pktinfo_addr.ip_address, ai.ip_port)
-
yield msg, UDPSource.new(sender_addrinfo, ai) {|reply_msg|
-
r.sendmsg reply_msg, 0, sender_addrinfo, pktinfo
-
}
-
else
-
yield msg, UDPSource.new(sender_addrinfo, ai) {|reply_msg|
-
r.send reply_msg, 0, sender_addrinfo
-
}
-
end
-
}
-
end
-
-
# :call-seq:
-
# Socket.udp_server_loop_on(sockets) {|msg, msg_src| ... }
-
#
-
# Run UDP/IP server loop on the given sockets.
-
#
-
# The return value of Socket.udp_server_sockets is appropriate for the argument.
-
#
-
# It calls the block for each message received.
-
#
-
1
def self.udp_server_loop_on(sockets, &b) # :yield: msg, msg_src
-
loop {
-
readable, _, _ = IO.select(sockets)
-
udp_server_recv(readable, &b)
-
}
-
end
-
-
# :call-seq:
-
# Socket.udp_server_loop(port) {|msg, msg_src| ... }
-
# Socket.udp_server_loop(host, port) {|msg, msg_src| ... }
-
#
-
# creates a UDP/IP server on _port_ and calls the block for each message arrived.
-
# The block is called with the message and its source information.
-
#
-
# This method allocates sockets internally using _port_.
-
# If _host_ is specified, it is used conjunction with _port_ to determine the server addresses.
-
#
-
# The _msg_ is a string.
-
#
-
# The _msg_src_ is a Socket::UDPSource object.
-
# It is used for reply.
-
#
-
# # UDP/IP echo server.
-
# Socket.udp_server_loop(9261) {|msg, msg_src|
-
# msg_src.reply msg
-
# }
-
#
-
1
def self.udp_server_loop(host=nil, port, &b) # :yield: message, message_source
-
udp_server_sockets(host, port) {|sockets|
-
udp_server_loop_on(sockets, &b)
-
}
-
end
-
-
# UDP/IP address information used by Socket.udp_server_loop.
-
1
class UDPSource
-
# +remote_adress+ is an Addrinfo object.
-
#
-
# +local_adress+ is an Addrinfo object.
-
#
-
# +reply_proc+ is a Proc used to send reply back to the source.
-
1
def initialize(remote_address, local_address, &reply_proc)
-
@remote_address = remote_address
-
@local_address = local_address
-
@reply_proc = reply_proc
-
end
-
-
# Address of the source
-
1
attr_reader :remote_address
-
-
# Local address
-
1
attr_reader :local_address
-
-
1
def inspect # :nodoc:
-
"\#<#{self.class}: #{@remote_address.inspect_sockaddr} to #{@local_address.inspect_sockaddr}>"
-
end
-
-
# Sends the String +msg+ to the source
-
1
def reply(msg)
-
@reply_proc.call msg
-
end
-
end
-
-
# creates a new socket connected to path using UNIX socket socket.
-
#
-
# If a block is given, the block is called with the socket.
-
# The value of the block is returned.
-
# The socket is closed when this method returns.
-
#
-
# If no block is given, the socket is returned.
-
#
-
# # talk to /tmp/sock socket.
-
# Socket.unix("/tmp/sock") {|sock|
-
# t = Thread.new { IO.copy_stream(sock, STDOUT) }
-
# IO.copy_stream(STDIN, sock)
-
# t.join
-
# }
-
#
-
1
def self.unix(path) # :yield: socket
-
addr = Addrinfo.unix(path)
-
sock = addr.connect
-
if block_given?
-
begin
-
yield sock
-
ensure
-
sock.close if !sock.closed?
-
end
-
else
-
sock
-
end
-
end
-
-
# creates a UNIX server socket on _path_
-
#
-
# If no block given, it returns a listening socket.
-
#
-
# If a block is given, it is called with the socket and the block value is returned.
-
# When the block exits, the socket is closed and the socket file is removed.
-
#
-
# socket = Socket.unix_server_socket("/tmp/s")
-
# p socket #=> #<Socket:fd 3>
-
# p socket.local_address #=> #<Addrinfo: /tmp/s SOCK_STREAM>
-
#
-
# Socket.unix_server_socket("/tmp/sock") {|s|
-
# p s #=> #<Socket:fd 3>
-
# p s.local_address #=> # #<Addrinfo: /tmp/sock SOCK_STREAM>
-
# }
-
#
-
1
def self.unix_server_socket(path)
-
begin
-
st = File.lstat(path)
-
rescue Errno::ENOENT
-
end
-
if st && st.socket? && st.owned?
-
File.unlink path
-
end
-
s = Addrinfo.unix(path).listen
-
if block_given?
-
begin
-
yield s
-
ensure
-
s.close if !s.closed?
-
File.unlink path
-
end
-
else
-
s
-
end
-
end
-
-
# creates a UNIX socket server on _path_.
-
# It calls the block for each socket accepted.
-
#
-
# If _host_ is specified, it is used with _port_ to determine the server ports.
-
#
-
# The socket is *not* closed when the block returns.
-
# So application should close it.
-
#
-
# This method deletes the socket file pointed by _path_ at first if
-
# the file is a socket file and it is owned by the user of the application.
-
# This is safe only if the directory of _path_ is not changed by a malicious user.
-
# So don't use /tmp/malicious-users-directory/socket.
-
# Note that /tmp/socket and /tmp/your-private-directory/socket is safe assuming that /tmp has sticky bit.
-
#
-
# # Sequential echo server.
-
# # It services only one client at a time.
-
# Socket.unix_server_loop("/tmp/sock") {|sock, client_addrinfo|
-
# begin
-
# IO.copy_stream(sock, sock)
-
# ensure
-
# sock.close
-
# end
-
# }
-
#
-
1
def self.unix_server_loop(path, &b) # :yield: socket, client_addrinfo
-
unix_server_socket(path) {|serv|
-
accept_loop(serv, &b)
-
}
-
end
-
-
end
-
-
#
-
# tempfile - manipulates temporary files
-
#
-
# $Id: tempfile.rb 33089 2011-08-26 23:54:49Z drbrain $
-
#
-
-
1
require 'delegate'
-
1
require 'tmpdir'
-
1
require 'thread'
-
-
# A utility class for managing temporary files. When you create a Tempfile
-
# object, it will create a temporary file with a unique filename. A Tempfile
-
# objects behaves just like a File object, and you can perform all the usual
-
# file operations on it: reading data, writing data, changing its permissions,
-
# etc. So although this class does not explicitly document all instance methods
-
# supported by File, you can in fact call any File instance method on a
-
# Tempfile object.
-
#
-
# == Synopsis
-
#
-
# require 'tempfile'
-
#
-
# file = Tempfile.new('foo')
-
# file.path # => A unique filename in the OS's temp directory,
-
# # e.g.: "/tmp/foo.24722.0"
-
# # This filename contains 'foo' in its basename.
-
# file.write("hello world")
-
# file.rewind
-
# file.read # => "hello world"
-
# file.close
-
# file.unlink # deletes the temp file
-
#
-
# == Good practices
-
#
-
# === Explicit close
-
#
-
# When a Tempfile object is garbage collected, or when the Ruby interpreter
-
# exits, its associated temporary file is automatically deleted. This means
-
# that's it's unnecessary to explicitly delete a Tempfile after use, though
-
# it's good practice to do so: not explicitly deleting unused Tempfiles can
-
# potentially leave behind large amounts of tempfiles on the filesystem
-
# until they're garbage collected. The existence of these temp files can make
-
# it harder to determine a new Tempfile filename.
-
#
-
# Therefore, one should always call #unlink or close in an ensure block, like
-
# this:
-
#
-
# file = Tempfile.new('foo')
-
# begin
-
# ...do something with file...
-
# ensure
-
# file.close
-
# file.unlink # deletes the temp file
-
# end
-
#
-
# === Unlink after creation
-
#
-
# On POSIX systems, it's possible to unlink a file right after creating it,
-
# and before closing it. This removes the filesystem entry without closing
-
# the file handle, so it ensures that only the processes that already had
-
# the file handle open can access the file's contents. It's strongly
-
# recommended that you do this if you do not want any other processes to
-
# be able to read from or write to the Tempfile, and you do not need to
-
# know the Tempfile's filename either.
-
#
-
# For example, a practical use case for unlink-after-creation would be this:
-
# you need a large byte buffer that's too large to comfortably fit in RAM,
-
# e.g. when you're writing a web server and you want to buffer the client's
-
# file upload data.
-
#
-
# Please refer to #unlink for more information and a code example.
-
#
-
# == Minor notes
-
#
-
# Tempfile's filename picking method is both thread-safe and inter-process-safe:
-
# it guarantees that no other threads or processes will pick the same filename.
-
#
-
# Tempfile itself however may not be entirely thread-safe. If you access the
-
# same Tempfile object from multiple threads then you should protect it with a
-
# mutex.
-
1
class Tempfile < DelegateClass(File)
-
1
MAX_TRY = 10 # :nodoc:
-
1
include Dir::Tmpname
-
-
# call-seq:
-
# new(basename, [tmpdir = Dir.tmpdir], [options])
-
#
-
# Creates a temporary file with permissions 0600 (= only readable and
-
# writable by the owner) and opens it with mode "w+".
-
#
-
# The +basename+ parameter is used to determine the name of the
-
# temporary file. You can either pass a String or an Array with
-
# 2 String elements. In the former form, the temporary file's base
-
# name will begin with the given string. In the latter form,
-
# the temporary file's base name will begin with the array's first
-
# element, and end with the second element. For example:
-
#
-
# file = Tempfile.new('hello')
-
# file.path # => something like: "/tmp/hello2843-8392-92849382--0"
-
#
-
# # Use the Array form to enforce an extension in the filename:
-
# file = Tempfile.new(['hello', '.jpg'])
-
# file.path # => something like: "/tmp/hello2843-8392-92849382--0.jpg"
-
#
-
# The temporary file will be placed in the directory as specified
-
# by the +tmpdir+ parameter. By default, this is +Dir.tmpdir+.
-
# When $SAFE > 0 and the given +tmpdir+ is tainted, it uses
-
# '/tmp' as the temporary directory. Please note that ENV values
-
# are tainted by default, and +Dir.tmpdir+'s return value might
-
# come from environment variables (e.g. <tt>$TMPDIR</tt>).
-
#
-
# file = Tempfile.new('hello', '/home/aisaka')
-
# file.path # => something like: "/home/aisaka/hello2843-8392-92849382--0"
-
#
-
# You can also pass an options hash. Under the hood, Tempfile creates
-
# the temporary file using +File.open+. These options will be passed to
-
# +File.open+. This is mostly useful for specifying encoding
-
# options, e.g.:
-
#
-
# Tempfile.new('hello', '/home/aisaka', :encoding => 'ascii-8bit')
-
#
-
# # You can also omit the 'tmpdir' parameter:
-
# Tempfile.new('hello', :encoding => 'ascii-8bit')
-
#
-
# === Exceptions
-
#
-
# If Tempfile.new cannot find a unique filename within a limited
-
# number of tries, then it will raise an exception.
-
1
def initialize(basename, *rest)
-
72
@data = []
-
72
@clean_proc = Remover.new(@data)
-
72
ObjectSpace.define_finalizer(self, @clean_proc)
-
-
72
create(basename, *rest) do |tmpname, n, opts|
-
72
mode = File::RDWR|File::CREAT|File::EXCL
-
72
perm = 0600
-
72
if opts
-
mode |= opts.delete(:mode) || 0
-
opts[:perm] = perm
-
perm = nil
-
else
-
72
opts = perm
-
end
-
72
self.class.locking(tmpname) do
-
71
@data[1] = @tmpfile = File.open(tmpname, mode, opts)
-
71
@data[0] = @tmpname = tmpname
-
end
-
71
@mode = mode & ~(File::CREAT|File::EXCL)
-
71
perm or opts.freeze
-
71
@opts = opts
-
end
-
-
71
super(@tmpfile)
-
end
-
-
# Opens or reopens the file with mode "r+".
-
1
def open
-
@tmpfile.close if @tmpfile
-
@tmpfile = File.open(@tmpname, @mode, @opts)
-
@data[1] = @tmpfile
-
__setobj__(@tmpfile)
-
end
-
-
1
def _close # :nodoc:
-
64
@tmpfile.close if @tmpfile
-
64
@tmpfile = nil
-
64
@data[1] = nil if @data
-
end
-
1
protected :_close
-
-
# Closes the file. If +unlink_now+ is true, then the file will be unlinked
-
# (deleted) after closing. Of course, you can choose to later call #unlink
-
# if you do not unlink it now.
-
#
-
# If you don't explicitly unlink the temporary file, the removal
-
# will be delayed until the object is finalized.
-
1
def close(unlink_now=false)
-
64
if unlink_now
-
1
close!
-
else
-
63
_close
-
end
-
end
-
-
# Closes and unlinks (deletes) the file. Has the same effect as called
-
# <tt>close(true)</tt>.
-
1
def close!
-
1
_close
-
1
unlink
-
1
ObjectSpace.undefine_finalizer(self)
-
end
-
-
# Unlinks (deletes) the file from the filesystem. One should always unlink
-
# the file after using it, as is explained in the "Explicit close" good
-
# practice section in the Tempfile overview:
-
#
-
# file = Tempfile.new('foo')
-
# begin
-
# ...do something with file...
-
# ensure
-
# file.close
-
# file.unlink # deletes the temp file
-
# end
-
#
-
# === Unlink-before-close
-
#
-
# On POSIX systems it's possible to unlink a file before closing it. This
-
# practice is explained in detail in the Tempfile overview (section
-
# "Unlink after creation"); please refer there for more information.
-
#
-
# However, unlink-before-close may not be supported on non-POSIX operating
-
# systems. Microsoft Windows is the most notable case: unlinking a non-closed
-
# file will result in an error, which this method will silently ignore. If
-
# you want to practice unlink-before-close whenever possible, then you should
-
# write code like this:
-
#
-
# file = Tempfile.new('foo')
-
# file.unlink # On Windows this silently fails.
-
# begin
-
# ... do something with file ...
-
# ensure
-
# file.close! # Closes the file handle. If the file wasn't unlinked
-
# # because #unlink failed, then this method will attempt
-
# # to do so again.
-
# end
-
1
def unlink
-
# keep this order for thread safeness
-
8
return unless @tmpname
-
8
begin
-
8
if File.exist?(@tmpname)
-
8
File.unlink(@tmpname)
-
end
-
# remove tmpname from remover
-
8
@data[0] = @data[2] = nil
-
8
@tmpname = nil
-
rescue Errno::EACCES
-
# may not be able to unlink on Windows; just ignore
-
end
-
end
-
1
alias delete unlink
-
-
# Returns the full path name of the temporary file.
-
# This will be nil if #unlink has been called.
-
1
def path
-
63
@tmpname
-
end
-
-
# Returns the size of the temporary file. As a side effect, the IO
-
# buffer is flushed before determining the size.
-
1
def size
-
if @tmpfile
-
@tmpfile.flush
-
@tmpfile.stat.size
-
elsif @tmpname
-
File.size(@tmpname)
-
else
-
0
-
end
-
end
-
1
alias length size
-
-
# :stopdoc:
-
1
class Remover
-
1
def initialize(data)
-
72
@pid = $$
-
72
@data = data
-
end
-
-
1
def call(*args)
-
70
if @pid == $$
-
70
path, tmpfile = *@data
-
-
70
STDERR.print "removing ", path, "..." if $DEBUG
-
-
70
tmpfile.close if tmpfile
-
-
# keep this order for thread safeness
-
70
if path
-
63
File.unlink(path) if File.exist?(path)
-
end
-
-
70
STDERR.print "done\n" if $DEBUG
-
end
-
end
-
end
-
# :startdoc:
-
-
1
class << self
-
# Creates a new Tempfile.
-
#
-
# If no block is given, this is a synonym for Tempfile.new.
-
#
-
# If a block is given, then a Tempfile object will be constructed,
-
# and the block is run with said object as argument. The Tempfile
-
# oject will be automatically closed after the block terminates.
-
# The call returns the value of the block.
-
#
-
# In any case, all arguments (+*args+) will be passed to Tempfile.new.
-
#
-
# Tempfile.open('foo', '/home/temp') do |f|
-
# ... do something with f ...
-
# end
-
#
-
# # Equivalent:
-
# f = Tempfile.open('foo', '/home/temp')
-
# begin
-
# ... do something with f ...
-
# ensure
-
# f.close
-
# end
-
1
def open(*args)
-
tempfile = new(*args)
-
-
if block_given?
-
begin
-
yield(tempfile)
-
ensure
-
tempfile.close
-
end
-
else
-
tempfile
-
end
-
end
-
-
# :stopdoc:
-
-
# yields with locking for +tmpname+ and returns the result of the
-
# block.
-
1
def locking(tmpname)
-
72
lock = tmpname + '.lock'
-
72
mkdir(lock)
-
71
yield
-
ensure
-
72
rmdir(lock) if lock
-
end
-
-
1
def mkdir(*args)
-
72
Dir.mkdir(*args)
-
end
-
-
1
def rmdir(*args)
-
72
Dir.rmdir(*args)
-
end
-
end
-
end
-
-
1
if __FILE__ == $0
-
# $DEBUG = true
-
f = Tempfile.new("foo")
-
f.print("foo\n")
-
f.close
-
f.open
-
p f.gets # => "foo\n"
-
f.close!
-
end
-
# Timeout long-running blocks
-
#
-
# == Synopsis
-
#
-
# require 'timeout'
-
# status = Timeout::timeout(5) {
-
# # Something that should be interrupted if it takes more than 5 seconds...
-
# }
-
#
-
# == Description
-
#
-
# Timeout provides a way to auto-terminate a potentially long-running
-
# operation if it hasn't finished in a fixed amount of time.
-
#
-
# Previous versions didn't use a module for namespacing, however
-
# #timeout is provided for backwards compatibility. You
-
# should prefer Timeout#timeout instead.
-
#
-
# == Copyright
-
#
-
# Copyright:: (C) 2000 Network Applied Communication Laboratory, Inc.
-
# Copyright:: (C) 2000 Information-technology Promotion Agency, Japan
-
-
1
module Timeout
-
# Raised by Timeout#timeout when the block times out.
-
1
class Error < RuntimeError
-
end
-
1
class ExitException < ::Exception # :nodoc:
-
end
-
-
# :stopdoc:
-
1
THIS_FILE = /\A#{Regexp.quote(__FILE__)}:/o
-
1
CALLER_OFFSET = ((c = caller[0]) && THIS_FILE =~ c) ? 1 : 0
-
# :startdoc:
-
-
# Perform an operation in a block, timing it out if it takes longer
-
# than +sec+ seconds to complete.
-
#
-
# +sec+:: Number of seconds to wait for the block to terminate. Any number
-
# may be used, including Floats to specify fractional seconds.
-
# +klass+:: Exception Class to raise if the block fails to terminate
-
# in +sec+ seconds. Omitting will use the default, Timeout::Error
-
#
-
# The block will be executed on another thread and will be given one
-
# argument: +sec+.
-
#
-
# Returns the result of the block *if* the block completed before
-
# +sec+ seconds, otherwise throws an exception, based on the value of +klass+.
-
#
-
# Note that this is both a method of module Timeout, so you can <tt>include
-
# Timeout</tt> into your classes so they have a #timeout method, as well as
-
# a module method, so you can call it directly as Timeout.timeout().
-
1
def timeout(sec, klass = nil) #:yield: +sec+
-
159
return yield(sec) if sec == nil or sec.zero?
-
159
exception = klass || Class.new(ExitException)
-
159
begin
-
159
begin
-
159
x = Thread.current
-
159
y = Thread.start {
-
159
begin
-
159
sleep sec
-
rescue => e
-
x.raise e
-
else
-
x.raise exception, "execution expired"
-
end
-
}
-
159
return yield(sec)
-
ensure
-
159
if y
-
159
y.kill
-
159
y.join # make sure y is dead.
-
end
-
end
-
rescue exception => e
-
rej = /\A#{Regexp.quote(__FILE__)}:#{__LINE__-4}\z/o
-
(bt = e.backtrace).reject! {|m| rej =~ m}
-
level = -caller(CALLER_OFFSET).size
-
while THIS_FILE =~ bt[level]
-
bt.delete_at(level)
-
level += 1
-
end
-
raise if klass # if exception class is specified, it
-
# would be expected outside.
-
raise Error, e.message, e.backtrace
-
end
-
end
-
-
1
module_function :timeout
-
end
-
-
# Identical to:
-
#
-
# Timeout::timeout(n, e, &block).
-
#
-
# This method is deprecated and provided only for backwards compatibility.
-
# You should use Timeout#timeout instead.
-
1
def timeout(n, e = nil, &block)
-
Timeout::timeout(n, e, &block)
-
end
-
-
# Another name for Timeout::Error, defined for backwards compatibility with
-
# earlier versions of timeout.rb.
-
1
TimeoutError = Timeout::Error
-
#
-
# tmpdir - retrieve temporary directory path
-
#
-
# $Id: tmpdir.rb 31635 2011-05-18 21:19:18Z drbrain $
-
#
-
-
1
require 'fileutils'
-
1
begin
-
1
require 'etc.so'
-
rescue LoadError
-
end
-
-
1
class Dir
-
-
1
@@systmpdir ||= defined?(Etc.systmpdir) ? Etc.systmpdir : '/tmp'
-
-
##
-
# Returns the operating system's temporary file path.
-
-
1
def Dir::tmpdir
-
11
tmp = '.'
-
11
if $SAFE > 0
-
tmp = @@systmpdir
-
else
-
11
for dir in [ENV['TMPDIR'], ENV['TMP'], ENV['TEMP'], @@systmpdir, '/tmp']
-
if dir and stat = File.stat(dir) and stat.directory? and stat.writable?
-
11
tmp = dir
-
11
break
-
44
end rescue nil
-
end
-
11
File.expand_path(tmp)
-
end
-
end
-
-
# Dir.mktmpdir creates a temporary directory.
-
#
-
# The directory is created with 0700 permission.
-
#
-
# The prefix and suffix of the name of the directory is specified by
-
# the optional first argument, <i>prefix_suffix</i>.
-
# - If it is not specified or nil, "d" is used as the prefix and no suffix is used.
-
# - If it is a string, it is used as the prefix and no suffix is used.
-
# - If it is an array, first element is used as the prefix and second element is used as a suffix.
-
#
-
# Dir.mktmpdir {|dir| dir is ".../d..." }
-
# Dir.mktmpdir("foo") {|dir| dir is ".../foo..." }
-
# Dir.mktmpdir(["foo", "bar"]) {|dir| dir is ".../foo...bar" }
-
#
-
# The directory is created under Dir.tmpdir or
-
# the optional second argument <i>tmpdir</i> if non-nil value is given.
-
#
-
# Dir.mktmpdir {|dir| dir is "#{Dir.tmpdir}/d..." }
-
# Dir.mktmpdir(nil, "/var/tmp") {|dir| dir is "/var/tmp/d..." }
-
#
-
# If a block is given,
-
# it is yielded with the path of the directory.
-
# The directory and its contents are removed
-
# using FileUtils.remove_entry_secure before Dir.mktmpdir returns.
-
# The value of the block is returned.
-
#
-
# Dir.mktmpdir {|dir|
-
# # use the directory...
-
# open("#{dir}/foo", "w") { ... }
-
# }
-
#
-
# If a block is not given,
-
# The path of the directory is returned.
-
# In this case, Dir.mktmpdir doesn't remove the directory.
-
#
-
# dir = Dir.mktmpdir
-
# begin
-
# # use the directory...
-
# open("#{dir}/foo", "w") { ... }
-
# ensure
-
# # remove the directory.
-
# FileUtils.remove_entry_secure dir
-
# end
-
#
-
1
def Dir.mktmpdir(prefix_suffix=nil, *rest)
-
path = Tmpname.create(prefix_suffix || "d", *rest) {|n| mkdir(n, 0700)}
-
if block_given?
-
begin
-
yield path
-
ensure
-
FileUtils.remove_entry_secure path
-
end
-
else
-
path
-
end
-
end
-
-
1
module Tmpname # :nodoc:
-
1
module_function
-
-
1
def tmpdir
-
9
Dir.tmpdir
-
end
-
-
1
def make_tmpname(prefix_suffix, n)
-
73
case prefix_suffix
-
when String
-
72
prefix = prefix_suffix
-
72
suffix = ""
-
when Array
-
1
prefix = prefix_suffix[0]
-
1
suffix = prefix_suffix[1]
-
else
-
raise ArgumentError, "unexpected prefix_suffix: #{prefix_suffix.inspect}"
-
end
-
73
t = Time.now.strftime("%Y%m%d")
-
73
path = "#{prefix}#{t}-#{$$}-#{rand(0x100000000).to_s(36)}"
-
73
path << "-#{n}" if n
-
73
path << suffix
-
end
-
-
1
def create(basename, *rest)
-
73
if opts = Hash.try_convert(rest[-1])
-
opts = opts.dup if rest.pop.equal?(opts)
-
max_try = opts.delete(:max_try)
-
opts = [opts]
-
else
-
73
opts = []
-
end
-
73
tmpdir, = *rest
-
73
if $SAFE > 0 and tmpdir.tainted?
-
tmpdir = '/tmp'
-
else
-
73
tmpdir ||= tmpdir()
-
end
-
73
n = nil
-
73
begin
-
73
path = File.expand_path(make_tmpname(basename, n), tmpdir)
-
73
yield(path, n, *opts)
-
rescue Errno::EEXIST
-
n ||= 0
-
n += 1
-
retry if !max_try or n < max_try
-
raise "cannot generate temporary name using `#{basename}' under `#{tmpdir}'"
-
end
-
72
path
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2004-2012 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
1
require 'simplecov'
-
1
SimpleCov.start
-
1
require 'active_support'
-
1
require 'active_support/rails'
-
1
require 'active_model/version'
-
-
1
module ActiveModel
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :AttributeMethods
-
1
autoload :BlockValidator, 'active_model/validator'
-
1
autoload :Callbacks
-
1
autoload :Conversion
-
1
autoload :Dirty
-
1
autoload :EachValidator, 'active_model/validator'
-
1
autoload :ForbiddenAttributesProtection
-
1
autoload :Lint
-
1
autoload :Model
-
1
autoload :DeprecatedMassAssignmentSecurity
-
1
autoload :Name, 'active_model/naming'
-
1
autoload :Naming
-
1
autoload :Observer, 'active_model/observing'
-
1
autoload :Observing
-
1
autoload :SecurePassword
-
1
autoload :Serialization
-
1
autoload :TestCase
-
1
autoload :Translation
-
1
autoload :Validations
-
1
autoload :Validator
-
-
1
eager_autoload do
-
1
autoload :Errors
-
end
-
-
1
module Serializers
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :JSON
-
1
autoload :Xml
-
end
-
end
-
-
1
def eager_load!
-
super
-
ActiveModel::Serializer.eager_load!
-
end
-
end
-
-
1
ActiveSupport.on_load(:i18n) do
-
1
I18n.load_path << File.dirname(__FILE__) + '/active_model/locale/en.yml'
-
end
-
-
1
module ActiveModel
-
# Raised when an attribute is not defined.
-
#
-
# class User < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# user = User.first
-
# user.pets.select(:id).first.user_id
-
# # => ActiveModel::MissingAttributeError: missing attribute: user_id
-
1
class MissingAttributeError < NoMethodError
-
end
-
# == Active \Model Attribute Methods
-
#
-
# <tt>ActiveModel::AttributeMethods</tt> provides a way to add prefixes and
-
# suffixes to your methods as well as handling the creation of Active Record
-
# like class methods such as +table_name+.
-
#
-
# The requirements to implement ActiveModel::AttributeMethods are to:
-
#
-
# * <tt>include ActiveModel::AttributeMethods</tt> in your object.
-
# * Call each Attribute Method module method you want to add, such as
-
# +attribute_method_suffix+ or +attribute_method_prefix+.
-
# * Call +define_attribute_methods+ after the other methods are called.
-
# * Define the various generic +_attribute+ methods that you have declared.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attribute_method_affix prefix: 'reset_', suffix: '_to_default!'
-
# attribute_method_suffix '_contrived?'
-
# attribute_method_prefix 'clear_'
-
# define_attribute_methods :name
-
#
-
# attr_accessor :name
-
#
-
# private
-
#
-
# def attribute_contrived?(attr)
-
# true
-
# end
-
#
-
# def clear_attribute(attr)
-
# send("#{attr}=", nil)
-
# end
-
#
-
# def reset_attribute_to_default!(attr)
-
# send("#{attr}=", 'Default Name')
-
# end
-
# end
-
#
-
# Note that whenever you include ActiveModel::AttributeMethods in your class,
-
# it requires you to implement an +attributes+ method which returns a hash
-
# with each attribute name in your model as hash key and the attribute value as
-
# hash value.
-
#
-
# Hash keys must be strings.
-
1
module AttributeMethods
-
1
extend ActiveSupport::Concern
-
-
1
NAME_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?=]?\z/
-
1
CALL_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?]?\z/
-
-
1
included do
-
1
class_attribute :attribute_aliases, :attribute_method_matchers, instance_writer: false
-
1
self.attribute_aliases = {}
-
1
self.attribute_method_matchers = [ClassMethods::AttributeMethodMatcher.new]
-
end
-
-
1
module ClassMethods
-
# Declares a method available for all attributes with the given prefix.
-
# Uses +method_missing+ and <tt>respond_to?</tt> to rewrite the method.
-
#
-
# #{prefix}#{attr}(*args, &block)
-
#
-
# to
-
#
-
# #{prefix}attribute(#{attr}, *args, &block)
-
#
-
# An instance method <tt>#{prefix}attribute</tt> must exist and accept
-
# at least the +attr+ argument.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_prefix 'clear_'
-
# define_attribute_methods :name
-
#
-
# private
-
#
-
# def clear_attribute(attr)
-
# send("#{attr}=", nil)
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name # => "Bob"
-
# person.clear_name
-
# person.name # => nil
-
1
def attribute_method_prefix(*prefixes)
-
self.attribute_method_matchers += prefixes.map! { |prefix| AttributeMethodMatcher.new prefix: prefix }
-
undefine_attribute_methods
-
end
-
-
# Declares a method available for all attributes with the given suffix.
-
# Uses +method_missing+ and <tt>respond_to?</tt> to rewrite the method.
-
#
-
# #{attr}#{suffix}(*args, &block)
-
#
-
# to
-
#
-
# attribute#{suffix}(#{attr}, *args, &block)
-
#
-
# An <tt>attribute#{suffix}</tt> instance method must exist and accept at
-
# least the +attr+ argument.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_suffix '_short?'
-
# define_attribute_methods :name
-
#
-
# private
-
#
-
# def attribute_short?(attr)
-
# send(attr).length < 5
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name # => "Bob"
-
# person.name_short? # => true
-
1
def attribute_method_suffix(*suffixes)
-
11
self.attribute_method_matchers += suffixes.map! { |suffix| AttributeMethodMatcher.new suffix: suffix }
-
4
undefine_attribute_methods
-
end
-
-
# Declares a method available for all attributes with the given prefix
-
# and suffix. Uses +method_missing+ and <tt>respond_to?</tt> to rewrite
-
# the method.
-
#
-
# #{prefix}#{attr}#{suffix}(*args, &block)
-
#
-
# to
-
#
-
# #{prefix}attribute#{suffix}(#{attr}, *args, &block)
-
#
-
# An <tt>#{prefix}attribute#{suffix}</tt> instance method must exist and
-
# accept at least the +attr+ argument.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_affix prefix: 'reset_', suffix: '_to_default!'
-
# define_attribute_methods :name
-
#
-
# private
-
#
-
# def reset_attribute_to_default!(attr)
-
# ...
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name # => 'Gem'
-
# person.reset_name_to_default!
-
# person.name # => 'Gemma'
-
1
def attribute_method_affix(*affixes)
-
2
self.attribute_method_matchers += affixes.map! { |affix| AttributeMethodMatcher.new prefix: affix[:prefix], suffix: affix[:suffix] }
-
1
undefine_attribute_methods
-
end
-
-
-
# Allows you to make aliases for attributes.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_suffix '_short?'
-
# define_attribute_methods :name
-
#
-
# alias_attribute :nickname, :name
-
#
-
# private
-
#
-
# def attribute_short?(attr)
-
# send(attr).length < 5
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name # => "Bob"
-
# person.nickname # => "Bob"
-
# person.name_short? # => true
-
# person.nickname_short? # => true
-
1
def alias_attribute(new_name, old_name)
-
self.attribute_aliases = attribute_aliases.merge(new_name.to_s => old_name.to_s)
-
attribute_method_matchers.each do |matcher|
-
matcher_new = matcher.method_name(new_name).to_s
-
matcher_old = matcher.method_name(old_name).to_s
-
define_proxy_call false, self, matcher_new, matcher_old
-
end
-
end
-
-
# Declares the attributes that should be prefixed and suffixed by
-
# ActiveModel::AttributeMethods.
-
#
-
# To use, pass attribute names (as strings or symbols), be sure to declare
-
# +define_attribute_methods+ after you define any prefix, suffix or affix
-
# methods, or they will not hook in.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name, :age, :address
-
# attribute_method_prefix 'clear_'
-
#
-
# # Call to define_attribute_methods must appear after the
-
# # attribute_method_prefix, attribute_method_suffix or
-
# # attribute_method_affix declares.
-
# define_attribute_methods :name, :age, :address
-
#
-
# private
-
#
-
# def clear_attribute(attr)
-
# ...
-
# end
-
# end
-
1
def define_attribute_methods(*attr_names)
-
attr_names.flatten.each { |attr_name| define_attribute_method(attr_name) }
-
end
-
-
# Declares an attribute that should be prefixed and suffixed by
-
# ActiveModel::AttributeMethods.
-
#
-
# To use, pass an attribute name (as string or symbol), be sure to declare
-
# +define_attribute_method+ after you define any prefix, suffix or affix
-
# method, or they will not hook in.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_suffix '_short?'
-
#
-
# # Call to define_attribute_method must appear after the
-
# # attribute_method_prefix, attribute_method_suffix or
-
# # attribute_method_affix declares.
-
# define_attribute_method :name
-
#
-
# private
-
#
-
# def attribute_short?(attr)
-
# send(attr).length < 5
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name # => "Bob"
-
# person.name_short? # => true
-
1
def define_attribute_method(attr_name)
-
attribute_method_matchers.each do |matcher|
-
method_name = matcher.method_name(attr_name)
-
-
unless instance_method_already_implemented?(method_name)
-
generate_method = "define_method_#{matcher.method_missing_target}"
-
-
if respond_to?(generate_method, true)
-
send(generate_method, attr_name)
-
else
-
define_proxy_call true, generated_attribute_methods, method_name, matcher.method_missing_target, attr_name.to_s
-
end
-
end
-
end
-
attribute_method_matchers_cache.clear
-
end
-
-
# Removes all the previously dynamically defined methods from the class.
-
#
-
# class Person
-
# include ActiveModel::AttributeMethods
-
#
-
# attr_accessor :name
-
# attribute_method_suffix '_short?'
-
# define_attribute_method :name
-
#
-
# private
-
#
-
# def attribute_short?(attr)
-
# send(attr).length < 5
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'Bob'
-
# person.name_short? # => true
-
#
-
# Person.undefine_attribute_methods
-
#
-
# person.name_short? # => NoMethodError
-
1
def undefine_attribute_methods
-
generated_attribute_methods.module_eval do
-
instance_methods.each { |m| undef_method(m) }
-
end
-
attribute_method_matchers_cache.clear
-
end
-
-
# Returns true if the attribute methods defined have been generated.
-
1
def generated_attribute_methods #:nodoc:
-
2
@generated_attribute_methods ||= Module.new.tap { |mod| include mod }
-
end
-
-
1
protected
-
1
def instance_method_already_implemented?(method_name) #:nodoc:
-
generated_attribute_methods.method_defined?(method_name)
-
end
-
-
1
private
-
# The methods +method_missing+ and +respond_to?+ of this module are
-
# invoked often in a typical rails, both of which invoke the method
-
# +match_attribute_method?+. The latter method iterates through an
-
# array doing regular expression matches, which results in a lot of
-
# object creations. Most of the times it returns a +nil+ match. As the
-
# match result is always the same given a +method_name+, this cache is
-
# used to alleviate the GC, which ultimately also speeds up the app
-
# significantly (in our case our test suite finishes 10% faster with
-
# this cache).
-
1
def attribute_method_matchers_cache #:nodoc:
-
@attribute_method_matchers_cache ||= {}
-
end
-
-
1
def attribute_method_matcher(method_name) #:nodoc:
-
attribute_method_matchers_cache.fetch(method_name) do |name|
-
# Must try to match prefixes/suffixes first, or else the matcher with no prefix/suffix
-
# will match every time.
-
matchers = attribute_method_matchers.partition(&:plain?).reverse.flatten(1)
-
match = nil
-
matchers.detect { |method| match = method.match(name) }
-
attribute_method_matchers_cache[name] = match
-
end
-
end
-
-
# Define a method `name` in `mod` that dispatches to `send`
-
# using the given `extra` args. This fallbacks `define_method`
-
# and `send` if the given names cannot be compiled.
-
1
def define_proxy_call(include_private, mod, name, send, *extra) #:nodoc:
-
defn = if name =~ NAME_COMPILABLE_REGEXP
-
"def #{name}(*args)"
-
else
-
"define_method(:'#{name}') do |*args|"
-
end
-
-
extra = (extra.map!(&:inspect) << "*args").join(", ")
-
-
target = if send =~ CALL_COMPILABLE_REGEXP
-
"#{"self." unless include_private}#{send}(#{extra})"
-
else
-
"send(:'#{send}', #{extra})"
-
end
-
-
mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1
-
#{defn}
-
#{target}
-
end
-
RUBY
-
end
-
-
1
class AttributeMethodMatcher #:nodoc:
-
1
attr_reader :prefix, :suffix, :method_missing_target
-
-
1
AttributeMethodMatch = Struct.new(:target, :attr_name, :method_name)
-
-
1
def initialize(options = {})
-
9
if options[:prefix] == '' || options[:suffix] == ''
-
message = "Specifying an empty prefix/suffix for an attribute method is no longer " \
-
"necessary. If the un-prefixed/suffixed version of the method has not been " \
-
"defined when `define_attribute_methods` is called, it will be defined " \
-
"automatically."
-
ActiveSupport::Deprecation.warn message
-
end
-
-
9
@prefix, @suffix = options.fetch(:prefix, ''), options.fetch(:suffix, '')
-
9
@regex = /^(?:#{Regexp.escape(@prefix)})(.*)(?:#{Regexp.escape(@suffix)})$/
-
9
@method_missing_target = "#{@prefix}attribute#{@suffix}"
-
9
@method_name = "#{prefix}%s#{suffix}"
-
end
-
-
1
def match(method_name)
-
if @regex =~ method_name
-
AttributeMethodMatch.new(method_missing_target, $1, method_name)
-
end
-
end
-
-
1
def method_name(attr_name)
-
@method_name % attr_name
-
end
-
-
1
def plain?
-
prefix.empty? && suffix.empty?
-
end
-
end
-
end
-
-
# Allows access to the object attributes, which are held in the
-
# <tt>@attributes</tt> hash, as though they were first-class methods. So a
-
# Person class with a name attribute can use Person#name and Person#name=
-
# and never directly use the attributes hash -- except for multiple assigns
-
# with ActiveRecord#attributes=. A Milestone class can also ask
-
# Milestone#completed? to test that the completed attribute is not +nil+
-
# or 0.
-
#
-
# It's also possible to instantiate related objects, so a Client class
-
# belonging to the clients table with a +master_id+ foreign key can
-
# instantiate master through Client#master.
-
1
def method_missing(method, *args, &block)
-
if respond_to_without_attributes?(method, true)
-
super
-
else
-
match = match_attribute_method?(method.to_s)
-
match ? attribute_missing(match, *args, &block) : super
-
end
-
end
-
-
# attribute_missing is like method_missing, but for attributes. When method_missing is
-
# called we check to see if there is a matching attribute method. If so, we call
-
# attribute_missing to dispatch the attribute. This method can be overloaded to
-
# customise the behaviour.
-
1
def attribute_missing(match, *args, &block)
-
__send__(match.target, match.attr_name, *args, &block)
-
end
-
-
# A Person object with a name attribute can ask <tt>person.respond_to?(:name)</tt>,
-
# <tt>person.respond_to?(:name=)</tt>, and <tt>person.respond_to?(:name?)</tt>
-
# which will all return +true+.
-
1
alias :respond_to_without_attributes? :respond_to?
-
1
def respond_to?(method, include_private_methods = false)
-
if super
-
true
-
elsif !include_private_methods && super(method, true)
-
# If we're here then we haven't found among non-private methods
-
# but found among all methods. Which means that the given method is private.
-
false
-
else
-
!match_attribute_method?(method.to_s).nil?
-
end
-
end
-
-
1
protected
-
1
def attribute_method?(attr_name) #:nodoc:
-
respond_to_without_attributes?(:attributes) && attributes.include?(attr_name)
-
end
-
-
1
private
-
# Returns a struct representing the matching attribute method.
-
# The struct's attributes are prefix, base and suffix.
-
1
def match_attribute_method?(method_name)
-
match = self.class.send(:attribute_method_matcher, method_name)
-
match if match && attribute_method?(match.attr_name)
-
end
-
-
1
def missing_attribute(attr_name, stack)
-
raise ActiveModel::MissingAttributeError, "missing attribute: #{attr_name}", stack
-
end
-
end
-
end
-
1
require 'active_support/callbacks'
-
-
1
module ActiveModel
-
# == Active \Model \Callbacks
-
#
-
# Provides an interface for any class to have Active Record like callbacks.
-
#
-
# Like the Active Record methods, the callback chain is aborted as soon as
-
# one of the methods in the chain returns +false+.
-
#
-
# First, extend ActiveModel::Callbacks from the class you are creating:
-
#
-
# class MyModel
-
# extend ActiveModel::Callbacks
-
# end
-
#
-
# Then define a list of methods that you want callbacks attached to:
-
#
-
# define_model_callbacks :create, :update
-
#
-
# This will provide all three standard callbacks (before, around and after)
-
# for both the <tt>:create</tt> and <tt>:update</tt> methods. To implement,
-
# you need to wrap the methods you want callbacks on in a block so that the
-
# callbacks get a chance to fire:
-
#
-
# def create
-
# run_callbacks :create do
-
# # Your create action methods here
-
# end
-
# end
-
#
-
# Then in your class, you can use the +before_create+, +after_create+ and
-
# +around_create+ methods, just as you would in an Active Record module.
-
#
-
# before_create :action_before_create
-
#
-
# def action_before_create
-
# # Your code here
-
# end
-
#
-
# When defining an around callback remember to yield to the block, otherwise
-
# it won't be executed:
-
#
-
# around_create :log_status
-
#
-
# def log_status
-
# puts 'going to call the block...'
-
# yield
-
# puts 'block successfully called.'
-
# end
-
#
-
# You can choose not to have all three callbacks by passing a hash to the
-
# +define_model_callbacks+ method.
-
#
-
# define_model_callbacks :create, only: [:after, :before]
-
#
-
# Would only create the +after_create+ and +before_create+ callback methods in
-
# your class.
-
1
module Callbacks
-
1
def self.extended(base) #:nodoc:
-
1
base.class_eval do
-
1
include ActiveSupport::Callbacks
-
end
-
end
-
-
# define_model_callbacks accepts the same options +define_callbacks+ does,
-
# in case you want to overwrite a default. Besides that, it also accepts an
-
# <tt>:only</tt> option, where you can choose if you want all types (before,
-
# around or after) or just some.
-
#
-
# define_model_callbacks :initializer, only: :after
-
#
-
# Note, the <tt>only: <type></tt> hash will apply to all callbacks defined
-
# on that method call. To get around this you can call the define_model_callbacks
-
# method as many times as you need.
-
#
-
# define_model_callbacks :create, only: :after
-
# define_model_callbacks :update, only: :before
-
# define_model_callbacks :destroy, only: :around
-
#
-
# Would create +after_create+, +before_update+ and +around_destroy+ methods
-
# only.
-
#
-
# You can pass in a class to before_<type>, after_<type> and around_<type>,
-
# in which case the callback will call that class's <action>_<type> method
-
# passing the object that the callback is being called on.
-
#
-
# class MyModel
-
# extend ActiveModel::Callbacks
-
# define_model_callbacks :create
-
#
-
# before_create AnotherClass
-
# end
-
#
-
# class AnotherClass
-
# def self.before_create( obj )
-
# # obj is the MyModel instance that the callback is being called on
-
# end
-
# end
-
1
def define_model_callbacks(*callbacks)
-
2
options = callbacks.extract_options!
-
2
options = {
-
:terminator => "result == false",
-
:skip_after_callbacks_if_terminated => true,
-
:scope => [:kind, :name],
-
:only => [:before, :around, :after]
-
}.merge!(options)
-
-
2
types = Array(options.delete(:only))
-
-
2
callbacks.each do |callback|
-
7
define_callbacks(callback, options)
-
-
7
types.each do |type|
-
15
send("_define_#{type}_model_callback", self, callback)
-
end
-
end
-
end
-
-
1
private
-
-
1
def _define_before_model_callback(klass, callback) #:nodoc:
-
4
klass.class_eval <<-CALLBACK, __FILE__, __LINE__ + 1
-
def self.before_#{callback}(*args, &block)
-
set_callback(:#{callback}, :before, *args, &block)
-
end
-
CALLBACK
-
end
-
-
1
def _define_around_model_callback(klass, callback) #:nodoc:
-
4
klass.class_eval <<-CALLBACK, __FILE__, __LINE__ + 1
-
def self.around_#{callback}(*args, &block)
-
set_callback(:#{callback}, :around, *args, &block)
-
end
-
CALLBACK
-
end
-
-
1
def _define_after_model_callback(klass, callback) #:nodoc:
-
7
klass.class_eval <<-CALLBACK, __FILE__, __LINE__ + 1
-
def self.after_#{callback}(*args, &block)
-
options = args.extract_options!
-
options[:prepend] = true
-
options[:if] = Array(options[:if]) << "value != false"
-
set_callback(:#{callback}, :after, *(args << options), &block)
-
end
-
CALLBACK
-
end
-
end
-
end
-
1
require 'active_support/inflector'
-
-
1
module ActiveModel
-
# == Active \Model Conversions
-
#
-
# Handles default conversions: to_model, to_key, to_param, and to_partial_path.
-
#
-
# Let's take for example this non-persisted object.
-
#
-
# class ContactMessage
-
# include ActiveModel::Conversion
-
#
-
# # ContactMessage are never persisted in the DB
-
# def persisted?
-
# false
-
# end
-
# end
-
#
-
# cm = ContactMessage.new
-
# cm.to_model == cm # => true
-
# cm.to_key # => nil
-
# cm.to_param # => nil
-
# cm.to_partial_path # => "contact_messages/contact_message"
-
1
module Conversion
-
1
extend ActiveSupport::Concern
-
-
# If your object is already designed to implement all of the Active Model
-
# you can use the default <tt>:to_model</tt> implementation, which simply
-
# returns +self+.
-
#
-
# class Person
-
# include ActiveModel::Conversion
-
# end
-
#
-
# person = Person.new
-
# person.to_model == person # => true
-
#
-
# If your model does not act like an Active Model object, then you should
-
# define <tt>:to_model</tt> yourself returning a proxy object that wraps
-
# your object with Active Model compliant methods.
-
1
def to_model
-
self
-
end
-
-
# Returns an Enumerable of all key attributes if any is set, regardless if
-
# the object is persisted or not. If there no key attributes, returns +nil+.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.create
-
# person.to_key # => [1]
-
1
def to_key
-
key = respond_to?(:id) && id
-
key ? [key] : nil
-
end
-
-
# Returns a +string+ representing the object's key suitable for use in URLs,
-
# or +nil+ if <tt>persisted?</tt> is +false+.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.create
-
# person.to_param # => "1"
-
1
def to_param
-
persisted? ? to_key.join('-') : nil
-
end
-
-
# Returns a +string+ identifying the path associated with the object.
-
# ActionPack uses this to find a suitable partial to represent the object.
-
#
-
# class Person
-
# include ActiveModel::Conversion
-
# end
-
#
-
# person = Person.new
-
# person.to_partial_path # => "people/person"
-
1
def to_partial_path
-
self.class._to_partial_path
-
end
-
-
1
module ClassMethods #:nodoc:
-
# Provide a class level cache for #to_partial_path. This is an
-
# internal method and should not be accessed directly.
-
1
def _to_partial_path #:nodoc:
-
@_to_partial_path ||= begin
-
element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(self))
-
collection = ActiveSupport::Inflector.tableize(self)
-
"#{collection}/#{element}".freeze
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
1
module DeprecatedMassAssignmentSecurity # :nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods # :nodoc:
-
1
def attr_protected(*args)
-
raise "`attr_protected` is extracted out of Rails into a gem. " \
-
"Please use new recommended protection model for params " \
-
"or add `protected_attributes` to your Gemfile to use old one."
-
end
-
-
1
def attr_accessible(*args)
-
raise "`attr_accessible` is extracted out of Rails into a gem. " \
-
"Please use new recommended protection model for params " \
-
"or add `protected_attributes` to your Gemfile to use old one."
-
end
-
end
-
end
-
end
-
1
require 'active_model/attribute_methods'
-
1
require 'active_support/hash_with_indifferent_access'
-
1
require 'active_support/core_ext/object/duplicable'
-
-
1
module ActiveModel
-
# == Active \Model \Dirty
-
#
-
# Provides a way to track changes in your object in the same way as
-
# Active Record does.
-
#
-
# The requirements for implementing ActiveModel::Dirty are:
-
#
-
# * <tt>include ActiveModel::Dirty</tt> in your object.
-
# * Call <tt>define_attribute_methods</tt> passing each method you want to
-
# track.
-
# * Call <tt>attr_name_will_change!</tt> before each change to the tracked
-
# attribute.
-
#
-
# If you wish to also track previous changes on save or update, you need to
-
# add:
-
#
-
# @previously_changed = changes
-
#
-
# inside of your save or update method.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# include ActiveModel::Dirty
-
#
-
# define_attribute_methods :name
-
#
-
# def name
-
# @name
-
# end
-
#
-
# def name=(val)
-
# name_will_change! unless val == @name
-
# @name = val
-
# end
-
#
-
# def save
-
# @previously_changed = changes
-
# @changed_attributes.clear
-
# end
-
# end
-
#
-
# A newly instantiated object is unchanged:
-
#
-
# person = Person.find_by_name('Uncle Bob')
-
# person.changed? # => false
-
#
-
# Change the name:
-
#
-
# person.name = 'Bob'
-
# person.changed? # => true
-
# person.name_changed? # => true
-
# person.name_was # => "Uncle Bob"
-
# person.name_change # => ["Uncle Bob", "Bob"]
-
# person.name = 'Bill'
-
# person.name_change # => ["Uncle Bob", "Bill"]
-
#
-
# Save the changes:
-
#
-
# person.save
-
# person.changed? # => false
-
# person.name_changed? # => false
-
#
-
# Assigning the same value leaves the attribute unchanged:
-
#
-
# person.name = 'Bill'
-
# person.name_changed? # => false
-
# person.name_change # => nil
-
#
-
# Which attributes have changed?
-
#
-
# person.name = 'Bob'
-
# person.changed # => ["name"]
-
# person.changes # => {"name" => ["Bill", "Bob"]}
-
#
-
# If an attribute is modified in-place then make use of <tt>[attribute_name]_will_change!</tt>
-
# to mark that the attribute is changing. Otherwise ActiveModel can't track
-
# changes to in-place attributes.
-
#
-
# person.name_will_change!
-
# person.name_change # => ["Bill", "Bill"]
-
# person.name << 'y'
-
# person.name_change # => ["Bill", "Billy"]
-
1
module Dirty
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::AttributeMethods
-
-
1
included do
-
1
attribute_method_suffix '_changed?', '_change', '_will_change!', '_was'
-
1
attribute_method_affix :prefix => 'reset_', :suffix => '!'
-
end
-
-
# Returns +true+ if any attribute have unsaved changes, +false+ otherwise.
-
#
-
# person.changed? # => false
-
# person.name = 'bob'
-
# person.changed? # => true
-
1
def changed?
-
changed_attributes.present?
-
end
-
-
# Returns an array with the name of the attributes with unsaved changes.
-
#
-
# person.changed # => []
-
# person.name = 'bob'
-
# person.changed # => ["name"]
-
1
def changed
-
changed_attributes.keys
-
end
-
-
# Returns a hash of changed attributes indicating their original
-
# and new values like <tt>attr => [original value, new value]</tt>.
-
#
-
# person.changes # => {}
-
# person.name = 'bob'
-
# person.changes # => { "name" => ["bill", "bob"] }
-
1
def changes
-
HashWithIndifferentAccess[changed.map { |attr| [attr, attribute_change(attr)] }]
-
end
-
-
# Returns a hash of attributes that were changed before the model was saved.
-
#
-
# person.name # => "bob"
-
# person.name = 'robert'
-
# person.save
-
# person.previous_changes # => {"name" => ["bob", "robert"]}
-
1
def previous_changes
-
@previously_changed
-
end
-
-
# Returns a hash of the attributes with unsaved changes indicating their original
-
# values like <tt>attr => original value</tt>.
-
#
-
# person.name # => "bob"
-
# person.name = 'robert'
-
# person.changed_attributes # => {"name" => "bob"}
-
1
def changed_attributes
-
@changed_attributes ||= {}
-
end
-
-
1
private
-
-
# Handle <tt>*_changed?</tt> for +method_missing+.
-
1
def attribute_changed?(attr)
-
changed_attributes.include?(attr)
-
end
-
-
# Handle <tt>*_change</tt> for +method_missing+.
-
1
def attribute_change(attr)
-
[changed_attributes[attr], __send__(attr)] if attribute_changed?(attr)
-
end
-
-
# Handle <tt>*_was</tt> for +method_missing+.
-
1
def attribute_was(attr)
-
attribute_changed?(attr) ? changed_attributes[attr] : __send__(attr)
-
end
-
-
# Handle <tt>*_will_change!</tt> for +method_missing+.
-
1
def attribute_will_change!(attr)
-
return if attribute_changed?(attr)
-
-
begin
-
value = __send__(attr)
-
value = value.duplicable? ? value.clone : value
-
rescue TypeError, NoMethodError
-
end
-
-
changed_attributes[attr] = value
-
end
-
-
# Handle <tt>reset_*!</tt> for +method_missing+.
-
1
def reset_attribute!(attr)
-
__send__("#{attr}=", changed_attributes[attr]) if attribute_changed?(attr)
-
end
-
end
-
end
-
# -*- coding: utf-8 -*-
-
-
1
require 'active_support/core_ext/array/conversions'
-
1
require 'active_support/core_ext/string/inflections'
-
-
1
module ActiveModel
-
# == Active \Model \Errors
-
#
-
# Provides a modified +Hash+ that you can include in your object
-
# for handling error messages and interacting with Action Pack helpers.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
#
-
# # Required dependency for ActiveModel::Errors
-
# extend ActiveModel::Naming
-
#
-
# def initialize
-
# @errors = ActiveModel::Errors.new(self)
-
# end
-
#
-
# attr_accessor :name
-
# attr_reader :errors
-
#
-
# def validate!
-
# errors.add(:name, "can not be nil") if name == nil
-
# end
-
#
-
# # The following methods are needed to be minimally implemented
-
#
-
# def read_attribute_for_validation(attr)
-
# send(attr)
-
# end
-
#
-
# def Person.human_attribute_name(attr, options = {})
-
# attr
-
# end
-
#
-
# def Person.lookup_ancestors
-
# [self]
-
# end
-
#
-
# end
-
#
-
# The last three methods are required in your object for Errors to be
-
# able to generate error messages correctly and also handle multiple
-
# languages. Of course, if you extend your object with ActiveModel::Translation
-
# you will not need to implement the last two. Likewise, using
-
# ActiveModel::Validations will handle the validation related methods
-
# for you.
-
#
-
# The above allows you to do:
-
#
-
# p = Person.new
-
# person.validate! # => ["can not be nil"]
-
# person.errors.full_messages # => ["name can not be nil"]
-
# # etc..
-
1
class Errors
-
1
include Enumerable
-
-
1
CALLBACKS_OPTIONS = [:if, :unless, :on, :allow_nil, :allow_blank, :strict]
-
-
1
attr_reader :messages
-
-
# Pass in the instance of the object that is using the errors object.
-
#
-
# class Person
-
# def initialize
-
# @errors = ActiveModel::Errors.new(self)
-
# end
-
# end
-
1
def initialize(base)
-
@base = base
-
@messages = {}
-
end
-
-
1
def initialize_dup(other) # :nodoc:
-
@messages = other.messages.dup
-
super
-
end
-
-
# Clear the error messages.
-
#
-
# person.errors.full_messages # => ["name can not be nil"]
-
# person.errors.clear
-
# person.errors.full_messages # => []
-
1
def clear
-
messages.clear
-
end
-
-
# Returns +true+ if the error messages include an error for the given key
-
# +attribute+, +false+ otherwise.
-
#
-
# person.errors.messages # => {:name=>["can not be nil"]}
-
# person.errors.include?(:name) # => true
-
# person.errors.include?(:age) # => false
-
1
def include?(attribute)
-
(v = messages[attribute]) && v.any?
-
end
-
# aliases include?
-
1
alias :has_key? :include?
-
-
# Get messages for +key+.
-
#
-
# person.errors.messages # => {:name=>["can not be nil"]}
-
# person.errors.get(:name) # => ["can not be nil"]
-
# person.errors.get(:age) # => nil
-
1
def get(key)
-
messages[key]
-
end
-
-
# Set messages for +key+ to +value+.
-
#
-
# person.errors.get(:name) # => ["can not be nil"]
-
# person.errors.set(:name, ["can't be nil"])
-
# person.errors.get(:name) # => ["can't be nil"]
-
1
def set(key, value)
-
messages[key] = value
-
end
-
-
# Delete messages for +key+. Returns the deleted messages.
-
#
-
# person.errors.get(:name) # => ["can not be nil"]
-
# person.errors.delete(:name) # => ["can not be nil"]
-
# person.errors.get(:name) # => nil
-
1
def delete(key)
-
messages.delete(key)
-
end
-
-
# When passed a symbol or a name of a method, returns an array of errors
-
# for the method.
-
#
-
# person.errors[:name] # => ["can not be nil"]
-
# person.errors['name'] # => ["can not be nil"]
-
1
def [](attribute)
-
get(attribute.to_sym) || set(attribute.to_sym, [])
-
end
-
-
# Adds to the supplied attribute the supplied error message.
-
#
-
# person.errors[:name] = "must be set"
-
# person.errors[:name] # => ['must be set']
-
1
def []=(attribute, error)
-
self[attribute] << error
-
end
-
-
# Iterates through each error key, value pair in the error messages hash.
-
# Yields the attribute and the error for that attribute. If the attribute
-
# has more than one error message, yields once for each error message.
-
#
-
# person.errors.add(:name, "can't be blank")
-
# person.errors.each do |attribute, error|
-
# # Will yield :name and "can't be blank"
-
# end
-
#
-
# person.errors.add(:name, "must be specified")
-
# person.errors.each do |attribute, error|
-
# # Will yield :name and "can't be blank"
-
# # then yield :name and "must be specified"
-
# end
-
1
def each
-
messages.each_key do |attribute|
-
self[attribute].each { |error| yield attribute, error }
-
end
-
end
-
-
# Returns the number of error messages.
-
#
-
# person.errors.add(:name, "can't be blank")
-
# person.errors.size # => 1
-
# person.errors.add(:name, "must be specified")
-
# person.errors.size # => 2
-
1
def size
-
values.flatten.size
-
end
-
-
# Returns all message values.
-
#
-
# person.errors.messages # => {:name=>["can not be nil", "must be specified"]}
-
# person.errors.values # => [["can not be nil", "must be specified"]]
-
1
def values
-
messages.values
-
end
-
-
# Returns all message keys.
-
#
-
# person.errors.messages # => {:name=>["can not be nil", "must be specified"]}
-
# person.errors.keys # => [:name]
-
1
def keys
-
messages.keys
-
end
-
-
# Returns an array of error messages, with the attribute name included.
-
#
-
# person.errors.add(:name, "can't be blank")
-
# person.errors.add(:name, "must be specified")
-
# person.errors.to_a # => ["name can't be blank", "name must be specified"]
-
1
def to_a
-
full_messages
-
end
-
-
# Returns the number of error messages.
-
#
-
# person.errors.add(:name, "can't be blank")
-
# person.errors.count # => 1
-
# person.errors.add(:name, "must be specified")
-
# person.errors.count # => 2
-
1
def count
-
to_a.size
-
end
-
-
# Returns +true+ if no errors are found, +false+ otherwise.
-
# If the error message is a string it can be empty.
-
#
-
# person.errors.full_messages # => ["name can not be nil"]
-
# person.errors.empty? # => false
-
1
def empty?
-
all? { |k, v| v && v.empty? && !v.is_a?(String) }
-
end
-
# aliases empty?
-
1
alias_method :blank?, :empty?
-
-
# Returns an xml formatted representation of the Errors hash.
-
#
-
# person.errors.add(:name, "can't be blank")
-
# person.errors.add(:name, "must be specified")
-
# person.errors.to_xml
-
# # =>
-
# # <?xml version=\"1.0\" encoding=\"UTF-8\"?>
-
# # <errors>
-
# # <error>name can't be blank</error>
-
# # <error>name must be specified</error>
-
# # </errors>
-
1
def to_xml(options={})
-
to_a.to_xml({ :root => "errors", :skip_types => true }.merge!(options))
-
end
-
-
# Returns a Hash that can be used as the JSON representation for this
-
# object. You can pass the <tt>:full_messages</tt> option. This determines
-
# if the json object should contain full messages or not (false by default).
-
#
-
# person.as_json # => {:name=>["can not be nil"]}
-
# person.as_json(full_messages: true) # => {:name=>["name can not be nil"]}
-
1
def as_json(options=nil)
-
to_hash(options && options[:full_messages])
-
end
-
-
# Returns a Hash of attributes with their error messages. If +full_messages+
-
# is +true+, it will contain full messages (see +full_message+).
-
#
-
# person.to_hash # => {:name=>["can not be nil"]}
-
# person.to_hash(true) # => {:name=>["name can not be nil"]}
-
1
def to_hash(full_messages = false)
-
if full_messages
-
messages = {}
-
self.messages.each do |attribute, array|
-
messages[attribute] = array.map { |message| full_message(attribute, message) }
-
end
-
messages
-
else
-
self.messages.dup
-
end
-
end
-
-
# Adds +message+ to the error messages on +attribute+. More than one error
-
# can be added to the same +attribute+. If no +message+ is supplied,
-
# <tt>:invalid</tt> is assumed.
-
#
-
# person.errors.add(:name)
-
# # => ["is invalid"]
-
# person.errors.add(:name, 'must be implemented')
-
# # => ["is invalid", "must be implemented"]
-
#
-
# person.errors.messages
-
# # => {:name=>["must be implemented", "is invalid"]}
-
#
-
# If +message+ is a symbol, it will be translated using the appropriate
-
# scope (see +generate_message+).
-
#
-
# If +message+ is a proc, it will be called, allowing for things like
-
# <tt>Time.now</tt> to be used within an error.
-
#
-
# If the <tt>:strict</tt> option is set to true will raise
-
# ActiveModel::StrictValidationFailed instead of adding the error.
-
# <tt>:strict</tt> option can also be set to any other exception.
-
#
-
# person.errors.add(:name, nil, strict: true)
-
# # => ActiveModel::StrictValidationFailed: name is invalid
-
# person.errors.add(:name, nil, strict: NameIsInvalid)
-
# # => NameIsInvalid: name is invalid
-
#
-
# person.errors.messages # => {}
-
1
def add(attribute, message = nil, options = {})
-
message = normalize_message(attribute, message, options)
-
if exception = options[:strict]
-
exception = ActiveModel::StrictValidationFailed if exception == true
-
raise exception, full_message(attribute, message)
-
end
-
-
self[attribute] << message
-
end
-
-
# Will add an error message to each of the attributes in +attributes+
-
# that is empty.
-
#
-
# person.errors.add_on_empty(:name)
-
# person.errors.messages
-
# # => {:name=>["can't be empty"]}
-
1
def add_on_empty(attributes, options = {})
-
Array(attributes).each do |attribute|
-
value = @base.send(:read_attribute_for_validation, attribute)
-
is_empty = value.respond_to?(:empty?) ? value.empty? : false
-
add(attribute, :empty, options) if value.nil? || is_empty
-
end
-
end
-
-
# Will add an error message to each of the attributes in +attributes+ that
-
# is blank (using Object#blank?).
-
#
-
# person.errors.add_on_blank(:name)
-
# person.errors.messages
-
# # => {:name=>["can't be blank"]}
-
1
def add_on_blank(attributes, options = {})
-
Array(attributes).each do |attribute|
-
value = @base.send(:read_attribute_for_validation, attribute)
-
add(attribute, :blank, options) if value.blank?
-
end
-
end
-
-
# Returns +true+ if an error on the attribute with the given message is
-
# present, +false+ otherwise. +message+ is treated the same as for +add+.
-
#
-
# person.errors.add :name, :blank
-
# person.errors.added? :name, :blank # => true
-
1
def added?(attribute, message = nil, options = {})
-
message = normalize_message(attribute, message, options)
-
self[attribute].include? message
-
end
-
-
# Returns all the full error messages in an array.
-
#
-
# class Person
-
# validates_presence_of :name, :address, :email
-
# validates_length_of :name, in: 5..30
-
# end
-
#
-
# person = Person.create(address: '123 First St.')
-
# person.errors.full_messages
-
# # => ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Email can't be blank"]
-
1
def full_messages
-
map { |attribute, message| full_message(attribute, message) }
-
end
-
-
# Returns a full message for a given attribute.
-
#
-
# person.errors.full_message(:name, 'is invalid') # => "Name is invalid"
-
1
def full_message(attribute, message)
-
return message if attribute == :base
-
attr_name = attribute.to_s.tr('.', '_').humanize
-
attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
-
I18n.t(:"errors.format", {
-
:default => "%{attribute} %{message}",
-
:attribute => attr_name,
-
:message => message
-
})
-
end
-
-
# Translates an error message in its default scope
-
# (<tt>activemodel.errors.messages</tt>).
-
#
-
# Error messages are first looked up in <tt>models.MODEL.attributes.ATTRIBUTE.MESSAGE</tt>,
-
# if it's not there, it's looked up in <tt>models.MODEL.MESSAGE</tt> and if
-
# that is not there also, it returns the translation of the default message
-
# (e.g. <tt>activemodel.errors.messages.MESSAGE</tt>). The translated model
-
# name, translated attribute name and the value are available for
-
# interpolation.
-
#
-
# When using inheritance in your models, it will check all the inherited
-
# models too, but only if the model itself hasn't been found. Say you have
-
# <tt>class Admin < User; end</tt> and you wanted the translation for
-
# the <tt>:blank</tt> error message for the <tt>title</tt> attribute,
-
# it looks for these translations:
-
#
-
# * <tt>activemodel.errors.models.admin.attributes.title.blank</tt>
-
# * <tt>activemodel.errors.models.admin.blank</tt>
-
# * <tt>activemodel.errors.models.user.attributes.title.blank</tt>
-
# * <tt>activemodel.errors.models.user.blank</tt>
-
# * any default you provided through the +options+ hash (in the <tt>activemodel.errors</tt> scope)
-
# * <tt>activemodel.errors.messages.blank</tt>
-
# * <tt>errors.attributes.title.blank</tt>
-
# * <tt>errors.messages.blank</tt>
-
1
def generate_message(attribute, type = :invalid, options = {})
-
type = options.delete(:message) if options[:message].is_a?(Symbol)
-
-
if @base.class.respond_to?(:i18n_scope)
-
defaults = @base.class.lookup_ancestors.map do |klass|
-
[ :"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.attributes.#{attribute}.#{type}",
-
:"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.#{type}" ]
-
end
-
else
-
defaults = []
-
end
-
-
defaults << options.delete(:message)
-
defaults << :"#{@base.class.i18n_scope}.errors.messages.#{type}" if @base.class.respond_to?(:i18n_scope)
-
defaults << :"errors.attributes.#{attribute}.#{type}"
-
defaults << :"errors.messages.#{type}"
-
-
defaults.compact!
-
defaults.flatten!
-
-
key = defaults.shift
-
value = (attribute != :base ? @base.send(:read_attribute_for_validation, attribute) : nil)
-
-
options = {
-
:default => defaults,
-
:model => @base.class.model_name.human,
-
:attribute => @base.class.human_attribute_name(attribute),
-
:value => value
-
}.merge!(options)
-
-
I18n.translate(key, options)
-
end
-
-
1
private
-
1
def normalize_message(attribute, message, options)
-
message ||= :invalid
-
-
case message
-
when Symbol
-
generate_message(attribute, message, options.except(*CALLBACKS_OPTIONS))
-
when Proc
-
message.call
-
else
-
message
-
end
-
end
-
end
-
-
# Raised when a validation cannot be corrected by end users and are considered
-
# exceptional.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
#
-
# validates_presence_of :name, strict: true
-
# end
-
#
-
# person = Person.new
-
# person.name = nil
-
# person.valid?
-
# # => ActiveModel::StrictValidationFailed: Name can't be blank
-
1
class StrictValidationFailed < StandardError
-
end
-
end
-
1
module ActiveModel
-
# Raised when forbidden attributes are used for mass assignment.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# params = ActionController::Parameters.new(name: 'Bob')
-
# Person.new(params)
-
# # => ActiveModel::ForbiddenAttributesError
-
#
-
# params.permit!
-
# Person.new(params)
-
# # => #<Person id: nil, name: "Bob">
-
1
class ForbiddenAttributesError < StandardError
-
end
-
-
1
module ForbiddenAttributesProtection # :nodoc:
-
1
protected
-
1
def sanitize_for_mass_assignment(attributes)
-
if attributes.respond_to?(:permitted?) && !attributes.permitted?
-
raise ActiveModel::ForbiddenAttributesError
-
else
-
attributes
-
end
-
end
-
end
-
end
-
1
require 'active_support/inflector'
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/module/introspection'
-
-
1
module ActiveModel
-
1
class Name
-
1
include Comparable
-
-
1
attr_reader :singular, :plural, :element, :collection,
-
:singular_route_key, :route_key, :param_key, :i18n_key,
-
:name
-
-
1
alias_method :cache_key, :collection
-
-
##
-
# :method: ==
-
#
-
# :call-seq:
-
# ==(other)
-
#
-
# Equivalent to <tt>String#==</tt>. Returns +true+ if the class name and
-
# +other+ are equal, otherwise +false+.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name == 'BlogPost' # => true
-
# BlogPost.model_name == 'Blog Post' # => false
-
-
##
-
# :method: ===
-
#
-
# :call-seq:
-
# ===(other)
-
#
-
# Equivalent to <tt>#==</tt>.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name === 'BlogPost' # => true
-
# BlogPost.model_name === 'Blog Post' # => false
-
-
##
-
# :method: <=>
-
#
-
# :call-seq:
-
# ==(other)
-
#
-
# Equivalent to <tt>String#<=></tt>.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name <=> 'BlogPost' # => 0
-
# BlogPost.model_name <=> 'Blog' # => 1
-
# BlogPost.model_name <=> 'BlogPosts' # => -1
-
-
##
-
# :method: =~
-
#
-
# :call-seq:
-
# =~(regexp)
-
#
-
# Equivalent to <tt>String#=~</tt>. Match the class name against the given
-
# regexp. Returns the position where the match starts or +nil+ if there is
-
# no match.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name =~ /Post/ # => 4
-
# BlogPost.model_name =~ /\d/ # => nil
-
-
##
-
# :method: !~
-
#
-
# :call-seq:
-
# !~(regexp)
-
#
-
# Equivalent to <tt>String#!~</tt>. Match the class name against the given
-
# regexp. Returns +true+ if there is no match, otherwise +false+.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name !~ /Post/ # => false
-
# BlogPost.model_name !~ /\d/ # => true
-
-
##
-
# :method: eql?
-
#
-
# :call-seq:
-
# eql?(other)
-
#
-
# Equivalent to <tt>String#eql?</tt>. Returns +true+ if the class name and
-
# +other+ have the same length and content, otherwise +false+.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name.eql?('BlogPost') # => true
-
# BlogPost.model_name.eql?('Blog Post') # => false
-
-
##
-
# :method: to_s
-
#
-
# :call-seq:
-
# to_s()
-
#
-
# Returns the class name.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name.to_s # => "BlogPost"
-
-
##
-
# :method: to_str
-
#
-
# :call-seq:
-
# to_str()
-
#
-
# Equivalent to +to_s+.
-
1
delegate :==, :===, :<=>, :=~, :"!~", :eql?, :to_s,
-
:to_str, :to => :name
-
-
# Returns a new ActiveModel::Name instance. By default, the +namespace+
-
# and +name+ option will take the namespace and name of the given class
-
# respectively.
-
#
-
# module Foo
-
# class Bar
-
# end
-
# end
-
#
-
# ActiveModel::Name.new(Foo::Bar).to_s
-
# # => "Foo::Bar"
-
1
def initialize(klass, namespace = nil, name = nil)
-
@name = name || klass.name
-
-
raise ArgumentError, "Class name cannot be blank. You need to supply a name argument when anonymous class given" if @name.blank?
-
-
@unnamespaced = @name.sub(/^#{namespace.name}::/, '') if namespace
-
@klass = klass
-
@singular = _singularize(@name)
-
@plural = ActiveSupport::Inflector.pluralize(@singular)
-
@element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(@name))
-
@human = ActiveSupport::Inflector.humanize(@element)
-
@collection = ActiveSupport::Inflector.tableize(@name)
-
@param_key = (namespace ? _singularize(@unnamespaced) : @singular)
-
@i18n_key = @name.underscore.to_sym
-
-
@route_key = (namespace ? ActiveSupport::Inflector.pluralize(@param_key) : @plural.dup)
-
@singular_route_key = ActiveSupport::Inflector.singularize(@route_key)
-
@route_key << "_index" if @plural == @singular
-
end
-
-
# Transform the model name into a more humane format, using I18n. By default,
-
# it will underscore then humanize the class name.
-
#
-
# class BlogPost
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BlogPost.model_name.human # => "Blog post"
-
#
-
# Specify +options+ with additional translating options.
-
1
def human(options={})
-
return @human unless @klass.respond_to?(:lookup_ancestors) &&
-
@klass.respond_to?(:i18n_scope)
-
-
defaults = @klass.lookup_ancestors.map do |klass|
-
klass.model_name.i18n_key
-
end
-
-
defaults << options[:default] if options[:default]
-
defaults << @human
-
-
options = { :scope => [@klass.i18n_scope, :models], :count => 1, :default => defaults }.merge!(options.except(:default))
-
I18n.translate(defaults.shift, options)
-
end
-
-
1
private
-
-
1
def _singularize(string, replacement='_')
-
ActiveSupport::Inflector.underscore(string).tr('/', replacement)
-
end
-
end
-
-
# == Active \Model \Naming
-
#
-
# Creates a +model_name+ method on your object.
-
#
-
# To implement, just extend ActiveModel::Naming in your object:
-
#
-
# class BookCover
-
# extend ActiveModel::Naming
-
# end
-
#
-
# BookCover.model_name # => "BookCover"
-
# BookCover.model_name.human # => "Book cover"
-
#
-
# BookCover.model_name.i18n_key # => :book_cover
-
# BookModule::BookCover.model_name.i18n_key # => :"book_module/book_cover"
-
#
-
# Providing the functionality that ActiveModel::Naming provides in your object
-
# is required to pass the Active Model Lint test. So either extending the
-
# provided method below, or rolling your own is required.
-
1
module Naming
-
# Returns an ActiveModel::Name object for module. It can be
-
# used to retrieve all kinds of naming-related information
-
# (See ActiveModel::Name for more information).
-
#
-
# class Person < ActiveModel::Model
-
# end
-
#
-
# Person.model_name # => Person
-
# Person.model_name.class # => ActiveModel::Name
-
# Person.model_name.singular # => "person"
-
# Person.model_name.plural # => "people"
-
1
def model_name
-
@_model_name ||= begin
-
namespace = self.parents.detect do |n|
-
n.respond_to?(:use_relative_model_naming?) && n.use_relative_model_naming?
-
end
-
ActiveModel::Name.new(self, namespace)
-
end
-
end
-
-
# Returns the plural class name of a record or class.
-
#
-
# ActiveModel::Naming.plural(post) # => "posts"
-
# ActiveModel::Naming.plural(Highrise::Person) # => "highrise_people"
-
1
def self.plural(record_or_class)
-
model_name_from_record_or_class(record_or_class).plural
-
end
-
-
# Returns the singular class name of a record or class.
-
#
-
# ActiveModel::Naming.singular(post) # => "post"
-
# ActiveModel::Naming.singular(Highrise::Person) # => "highrise_person"
-
1
def self.singular(record_or_class)
-
model_name_from_record_or_class(record_or_class).singular
-
end
-
-
# Identifies whether the class name of a record or class is uncountable.
-
#
-
# ActiveModel::Naming.uncountable?(Sheep) # => true
-
# ActiveModel::Naming.uncountable?(Post) # => false
-
1
def self.uncountable?(record_or_class)
-
plural(record_or_class) == singular(record_or_class)
-
end
-
-
# Returns string to use while generating route names. It differs for
-
# namespaced models regarding whether it's inside isolated engine.
-
#
-
# # For isolated engine:
-
# ActiveModel::Naming.singular_route_key(Blog::Post) #=> post
-
#
-
# # For shared engine:
-
# ActiveModel::Naming.singular_route_key(Blog::Post) #=> blog_post
-
1
def self.singular_route_key(record_or_class)
-
model_name_from_record_or_class(record_or_class).singular_route_key
-
end
-
-
# Returns string to use while generating route names. It differs for
-
# namespaced models regarding whether it's inside isolated engine.
-
#
-
# # For isolated engine:
-
# ActiveModel::Naming.route_key(Blog::Post) #=> posts
-
#
-
# # For shared engine:
-
# ActiveModel::Naming.route_key(Blog::Post) #=> blog_posts
-
#
-
# The route key also considers if the noun is uncountable and, in
-
# such cases, automatically appends _index.
-
1
def self.route_key(record_or_class)
-
model_name_from_record_or_class(record_or_class).route_key
-
end
-
-
# Returns string to use for params names. It differs for
-
# namespaced models regarding whether it's inside isolated engine.
-
#
-
# # For isolated engine:
-
# ActiveModel::Naming.param_key(Blog::Post) #=> post
-
#
-
# # For shared engine:
-
# ActiveModel::Naming.param_key(Blog::Post) #=> blog_post
-
1
def self.param_key(record_or_class)
-
model_name_from_record_or_class(record_or_class).param_key
-
end
-
-
1
def self.model_name_from_record_or_class(record_or_class) #:nodoc:
-
if record_or_class.respond_to?(:model_name)
-
record_or_class.model_name
-
elsif record_or_class.respond_to?(:to_model)
-
record_or_class.to_model.class.model_name
-
else
-
record_or_class.class.model_name
-
end
-
end
-
1
private_class_method :model_name_from_record_or_class
-
end
-
end
-
1
require 'set'
-
-
1
module ActiveModel
-
# Stores the enabled/disabled state of individual observers for
-
# a particular model class.
-
1
class ObserverArray < Array
-
1
attr_reader :model_class
-
1
def initialize(model_class, *args) #:nodoc:
-
@model_class = model_class
-
super(*args)
-
end
-
-
# Returns +true+ if the given observer is disabled for the model class,
-
# +false+ otherwise.
-
1
def disabled_for?(observer) #:nodoc:
-
disabled_observers.include?(observer.class)
-
end
-
-
# Disables one or more observers. This supports multiple forms:
-
#
-
# ORM.observers.disable :all
-
# # => disables all observers for all models subclassed from
-
# # an ORM base class that includes ActiveModel::Observing
-
# # e.g. ActiveRecord::Base
-
#
-
# ORM.observers.disable :user_observer
-
# # => disables the UserObserver
-
#
-
# User.observers.disable AuditTrail
-
# # => disables the AuditTrail observer for User notifications.
-
# # Other models will still notify the AuditTrail observer.
-
#
-
# ORM.observers.disable :observer_1, :observer_2
-
# # => disables Observer1 and Observer2 for all models.
-
#
-
# User.observers.disable :all do
-
# # all user observers are disabled for
-
# # just the duration of the block
-
# end
-
1
def disable(*observers, &block)
-
set_enablement(false, observers, &block)
-
end
-
-
# Enables one or more observers. This supports multiple forms:
-
#
-
# ORM.observers.enable :all
-
# # => enables all observers for all models subclassed from
-
# # an ORM base class that includes ActiveModel::Observing
-
# # e.g. ActiveRecord::Base
-
#
-
# ORM.observers.enable :user_observer
-
# # => enables the UserObserver
-
#
-
# User.observers.enable AuditTrail
-
# # => enables the AuditTrail observer for User notifications.
-
# # Other models will not be affected (i.e. they will not
-
# # trigger notifications to AuditTrail if previously disabled)
-
#
-
# ORM.observers.enable :observer_1, :observer_2
-
# # => enables Observer1 and Observer2 for all models.
-
#
-
# User.observers.enable :all do
-
# # all user observers are enabled for
-
# # just the duration of the block
-
# end
-
#
-
# Note: all observers are enabled by default. This method is only
-
# useful when you have previously disabled one or more observers.
-
1
def enable(*observers, &block)
-
set_enablement(true, observers, &block)
-
end
-
-
1
protected
-
-
1
def disabled_observers #:nodoc:
-
@disabled_observers ||= Set.new
-
end
-
-
1
def observer_class_for(observer) #:nodoc:
-
return observer if observer.is_a?(Class)
-
-
if observer.respond_to?(:to_sym) # string/symbol
-
observer.to_s.camelize.constantize
-
else
-
raise ArgumentError, "#{observer} was not a class or a " +
-
"lowercase, underscored class name as expected."
-
end
-
end
-
-
1
def start_transaction #:nodoc:
-
disabled_observer_stack.push(disabled_observers.dup)
-
each_subclass_array do |array|
-
array.start_transaction
-
end
-
end
-
-
1
def disabled_observer_stack #:nodoc:
-
@disabled_observer_stack ||= []
-
end
-
-
1
def end_transaction #:nodoc:
-
@disabled_observers = disabled_observer_stack.pop
-
each_subclass_array do |array|
-
array.end_transaction
-
end
-
end
-
-
1
def transaction #:nodoc:
-
start_transaction
-
-
begin
-
yield
-
ensure
-
end_transaction
-
end
-
end
-
-
1
def each_subclass_array #:nodoc:
-
model_class.descendants.each do |subclass|
-
yield subclass.observers
-
end
-
end
-
-
1
def set_enablement(enabled, observers) #:nodoc:
-
if block_given?
-
transaction do
-
set_enablement(enabled, observers)
-
yield
-
end
-
else
-
observers = ActiveModel::Observer.descendants if observers == [:all]
-
observers.each do |obs|
-
klass = observer_class_for(obs)
-
-
unless klass < ActiveModel::Observer
-
raise ArgumentError.new("#{obs} does not refer to a valid observer")
-
end
-
-
if enabled
-
disabled_observers.delete(klass)
-
else
-
disabled_observers << klass
-
end
-
end
-
-
each_subclass_array do |array|
-
array.set_enablement(enabled, observers)
-
end
-
end
-
end
-
end
-
end
-
1
require 'singleton'
-
1
require 'active_model/observer_array'
-
1
require 'active_support/core_ext/module/aliasing'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/core_ext/enumerable'
-
1
require 'active_support/core_ext/object/try'
-
1
require 'active_support/descendants_tracker'
-
-
1
module ActiveModel
-
# == Active \Model Observers Activation
-
1
module Observing
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
extend ActiveSupport::DescendantsTracker
-
end
-
-
1
module ClassMethods
-
# Activates the observers assigned.
-
#
-
# class ORM
-
# include ActiveModel::Observing
-
# end
-
#
-
# # Calls PersonObserver.instance
-
# ORM.observers = :person_observer
-
#
-
# # Calls Cacher.instance and GarbageCollector.instance
-
# ORM.observers = :cacher, :garbage_collector
-
#
-
# # Same as above, just using explicit class references
-
# ORM.observers = Cacher, GarbageCollector
-
#
-
# Note: Setting this does not instantiate the observers yet.
-
# <tt>instantiate_observers</tt> is called during startup, and before
-
# each development request.
-
1
def observers=(*values)
-
observers.replace(values.flatten)
-
end
-
-
# Gets an array of observers observing this model. The array also provides
-
# +enable+ and +disable+ methods that allow you to selectively enable and
-
# disable observers (see ActiveModel::ObserverArray.enable and
-
# ActiveModel::ObserverArray.disable for more on this).
-
#
-
# class ORM
-
# include ActiveModel::Observing
-
# end
-
#
-
# ORM.observers = :cacher, :garbage_collector
-
# ORM.observers # => [:cacher, :garbage_collector]
-
# ORM.observers.class # => ActiveModel::ObserverArray
-
1
def observers
-
@observers ||= ObserverArray.new(self)
-
end
-
-
# Returns the current observer instances.
-
#
-
# class Foo
-
# include ActiveModel::Observing
-
#
-
# attr_accessor :status
-
# end
-
#
-
# class FooObserver < ActiveModel::Observer
-
# def on_spec(record, *args)
-
# record.status = true
-
# end
-
# end
-
#
-
# Foo.observers = FooObserver
-
# Foo.instantiate_observers
-
#
-
# Foo.observer_instances # => [#<FooObserver:0x007fc212c40820>]
-
1
def observer_instances
-
1
@observer_instances ||= []
-
end
-
-
# Instantiate the global observers.
-
#
-
# class Foo
-
# include ActiveModel::Observing
-
#
-
# attr_accessor :status
-
# end
-
#
-
# class FooObserver < ActiveModel::Observer
-
# def on_spec(record, *args)
-
# record.status = true
-
# end
-
# end
-
#
-
# Foo.observers = FooObserver
-
#
-
# foo = Foo.new
-
# foo.status = false
-
# foo.notify_observers(:on_spec)
-
# foo.status # => false
-
#
-
# Foo.instantiate_observers # => [FooObserver]
-
#
-
# foo = Foo.new
-
# foo.status = false
-
# foo.notify_observers(:on_spec)
-
# foo.status # => true
-
1
def instantiate_observers
-
observers.each { |o| instantiate_observer(o) }
-
end
-
-
# Add a new observer to the pool. The new observer needs to respond to
-
# <tt>update</tt>, otherwise it raises an +ArgumentError+ exception.
-
#
-
# class Foo
-
# include ActiveModel::Observing
-
# end
-
#
-
# class FooObserver < ActiveModel::Observer
-
# end
-
#
-
# Foo.add_observer(FooObserver.instance)
-
#
-
# Foo.observers_instance
-
# # => [#<FooObserver:0x007fccf55d9390>]
-
1
def add_observer(observer)
-
unless observer.respond_to? :update
-
raise ArgumentError, "observer needs to respond to 'update'"
-
end
-
observer_instances << observer
-
end
-
-
# Fires notifications to model's observers.
-
#
-
# def save
-
# notify_observers(:before_save)
-
# ...
-
# notify_observers(:after_save)
-
# end
-
#
-
# Custom notifications can be sent in a similar fashion:
-
#
-
# notify_observers(:custom_notification, :foo)
-
#
-
# This will call <tt>custom_notification</tt>, passing as arguments
-
# the current object and <tt>:foo</tt>.
-
1
def notify_observers(*args)
-
1
observer_instances.each { |observer| observer.update(*args) }
-
end
-
-
# Returns the total number of instantiated observers.
-
#
-
# class Foo
-
# include ActiveModel::Observing
-
#
-
# attr_accessor :status
-
# end
-
#
-
# class FooObserver < ActiveModel::Observer
-
# def on_spec(record, *args)
-
# record.status = true
-
# end
-
# end
-
#
-
# Foo.observers = FooObserver
-
# Foo.observers_count # => 0
-
# Foo.instantiate_observers
-
# Foo.observers_count # => 1
-
1
def observers_count
-
observer_instances.size
-
end
-
-
# <tt>count_observers</tt> is deprecated. Use #observers_count.
-
1
def count_observers
-
msg = "count_observers is deprecated in favor of observers_count"
-
ActiveSupport::Deprecation.warn msg
-
observers_count
-
end
-
-
1
protected
-
1
def instantiate_observer(observer) #:nodoc:
-
# string/symbol
-
if observer.respond_to?(:to_sym)
-
observer = observer.to_s.camelize.constantize
-
end
-
if observer.respond_to?(:instance)
-
observer.instance
-
else
-
raise ArgumentError,
-
"#{observer} must be a lowercase, underscored class name (or " +
-
"the class itself) responding to the method :instance. " +
-
"Example: Person.observers = :big_brother # calls " +
-
"BigBrother.instance"
-
end
-
end
-
-
# Notify observers when the observed class is subclassed.
-
1
def inherited(subclass) #:nodoc:
-
1
super
-
1
notify_observers :observed_class_inherited, subclass
-
end
-
end
-
-
# Notify a change to the list of observers.
-
#
-
# class Foo
-
# include ActiveModel::Observing
-
#
-
# attr_accessor :status
-
# end
-
#
-
# class FooObserver < ActiveModel::Observer
-
# def on_spec(record, *args)
-
# record.status = true
-
# end
-
# end
-
#
-
# Foo.observers = FooObserver
-
# Foo.instantiate_observers # => [FooObserver]
-
#
-
# foo = Foo.new
-
# foo.status = false
-
# foo.notify_observers(:on_spec)
-
# foo.status # => true
-
#
-
# See ActiveModel::Observing::ClassMethods.notify_observers for more
-
# information.
-
1
def notify_observers(method, *extra_args)
-
self.class.notify_observers(method, self, *extra_args)
-
end
-
end
-
-
# == Active \Model Observers
-
#
-
# Observer classes respond to life cycle callbacks to implement trigger-like
-
# behavior outside the original class. This is a great way to reduce the
-
# clutter that normally comes when the model class is burdened with
-
# functionality that doesn't pertain to the core responsibility of the
-
# class.
-
#
-
# class CommentObserver < ActiveModel::Observer
-
# def after_save(comment)
-
# Notifications.comment('admin@do.com', 'New comment was posted', comment).deliver
-
# end
-
# end
-
#
-
# This Observer sends an email when a <tt>Comment#save</tt> is finished.
-
#
-
# class ContactObserver < ActiveModel::Observer
-
# def after_create(contact)
-
# contact.logger.info('New contact added!')
-
# end
-
#
-
# def after_destroy(contact)
-
# contact.logger.warn("Contact with an id of #{contact.id} was destroyed!")
-
# end
-
# end
-
#
-
# This Observer uses logger to log when specific callbacks are triggered.
-
#
-
# == \Observing a class that can't be inferred
-
#
-
# Observers will by default be mapped to the class with which they share a
-
# name. So <tt>CommentObserver</tt> will be tied to observing <tt>Comment</tt>,
-
# <tt>ProductManagerObserver</tt> to <tt>ProductManager</tt>, and so on. If
-
# you want to name your observer differently than the class you're interested
-
# in observing, you can use the <tt>Observer.observe</tt> class method which
-
# takes either the concrete class (<tt>Product</tt>) or a symbol for that
-
# class (<tt>:product</tt>):
-
#
-
# class AuditObserver < ActiveModel::Observer
-
# observe :account
-
#
-
# def after_update(account)
-
# AuditTrail.new(account, 'UPDATED')
-
# end
-
# end
-
#
-
# If the audit observer needs to watch more than one kind of object, this can
-
# be specified with multiple arguments:
-
#
-
# class AuditObserver < ActiveModel::Observer
-
# observe :account, :balance
-
#
-
# def after_update(record)
-
# AuditTrail.new(record, 'UPDATED')
-
# end
-
# end
-
#
-
# The <tt>AuditObserver</tt> will now act on both updates to <tt>Account</tt>
-
# and <tt>Balance</tt> by treating them both as records.
-
#
-
# If you're using an Observer in a Rails application with Active Record, be
-
# sure to read about the necessary configuration in the documentation for
-
# ActiveRecord::Observer.
-
1
class Observer
-
1
include Singleton
-
1
extend ActiveSupport::DescendantsTracker
-
-
1
class << self
-
# Attaches the observer to the supplied model classes.
-
#
-
# class AuditObserver < ActiveModel::Observer
-
# observe :account, :balance
-
# end
-
#
-
# AuditObserver.observed_classes # => [Account, Balance]
-
1
def observe(*models)
-
models.flatten!
-
models.collect! { |model| model.respond_to?(:to_sym) ? model.to_s.camelize.constantize : model }
-
singleton_class.redefine_method(:observed_classes) { models }
-
end
-
-
# Returns an array of Classes to observe.
-
#
-
# AccountObserver.observed_classes # => [Account]
-
#
-
# You can override this instead of using the +observe+ helper.
-
#
-
# class AuditObserver < ActiveModel::Observer
-
# def self.observed_classes
-
# [Account, Balance]
-
# end
-
# end
-
1
def observed_classes
-
Array(observed_class)
-
end
-
-
# Returns the class observed by default. It's inferred from the observer's
-
# class name.
-
#
-
# PersonObserver.observed_class # => Person
-
# AccountObserver.observed_class # => Account
-
1
def observed_class
-
name[/(.*)Observer/, 1].try :constantize
-
end
-
end
-
-
# Start observing the declared classes and their subclasses.
-
# Called automatically by the instance method.
-
1
def initialize #:nodoc:
-
observed_classes.each { |klass| add_observer!(klass) }
-
end
-
-
1
def observed_classes #:nodoc:
-
self.class.observed_classes
-
end
-
-
# Send observed_method(object) if the method exists and
-
# the observer is enabled for the given object's class.
-
1
def update(observed_method, object, *extra_args, &block) #:nodoc:
-
return if !respond_to?(observed_method) || disabled_for?(object)
-
send(observed_method, object, *extra_args, &block)
-
end
-
-
# Special method sent by the observed class when it is inherited.
-
# Passes the new subclass.
-
1
def observed_class_inherited(subclass) #:nodoc:
-
self.class.observe(observed_classes + [subclass])
-
add_observer!(subclass)
-
end
-
-
1
protected
-
1
def add_observer!(klass) #:nodoc:
-
klass.add_observer(self)
-
end
-
-
# Returns true if notifications are disabled for this object.
-
1
def disabled_for?(object) #:nodoc:
-
klass = object.class
-
return false unless klass.respond_to?(:observers)
-
klass.observers.disabled_for?(self)
-
end
-
end
-
end
-
1
module ActiveModel
-
1
module SecurePassword
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
# Adds methods to set and authenticate against a BCrypt password.
-
# This mechanism requires you to have a password_digest attribute.
-
#
-
# Validations for presence of password on create, confirmation of password
-
# (using a +password_confirmation+ attribute) are automatically added. If
-
# you wish to turn off validations, pass <tt>validations: false</tt> as an
-
# argument. You can add more validations by hand if need be.
-
#
-
# You need to add bcrypt-ruby (~> 3.0.0) to Gemfile to use #has_secure_password:
-
#
-
# gem 'bcrypt-ruby', '~> 3.0.0'
-
#
-
# Example using Active Record (which automatically includes ActiveModel::SecurePassword):
-
#
-
# # Schema: User(name:string, password_digest:string)
-
# class User < ActiveRecord::Base
-
# has_secure_password
-
# end
-
#
-
# user = User.new(name: 'david', password: '', password_confirmation: 'nomatch')
-
# user.save # => false, password required
-
# user.password = 'mUc3m00RsqyRe'
-
# user.save # => false, confirmation doesn't match
-
# user.password_confirmation = 'mUc3m00RsqyRe'
-
# user.save # => true
-
# user.authenticate('notright') # => false
-
# user.authenticate('mUc3m00RsqyRe') # => user
-
# User.find_by_name('david').try(:authenticate, 'notright') # => false
-
# User.find_by_name('david').try(:authenticate, 'mUc3m00RsqyRe') # => user
-
1
def has_secure_password(options = {})
-
# Load bcrypt-ruby only when has_secure_password is used.
-
# This is to avoid ActiveModel (and by extension the entire framework)
-
# being dependent on a binary library.
-
gem 'bcrypt-ruby', '~> 3.0.0'
-
require 'bcrypt'
-
-
attr_reader :password
-
-
if options.fetch(:validations, true)
-
validates_confirmation_of :password
-
validates_presence_of :password, :on => :create
-
-
before_create { raise "Password digest missing on new record" if password_digest.blank? }
-
end
-
-
include InstanceMethodsOnActivation
-
-
if respond_to?(:attributes_protected_by_default)
-
def self.attributes_protected_by_default #:nodoc:
-
super + ['password_digest']
-
end
-
end
-
end
-
end
-
-
1
module InstanceMethodsOnActivation
-
# Returns +self+ if the password is correct, otherwise +false+.
-
#
-
# class User < ActiveRecord::Base
-
# has_secure_password validations: false
-
# end
-
#
-
# user = User.new(name: 'david', password: 'mUc3m00RsqyRe')
-
# user.save
-
# user.authenticate('notright') # => false
-
# user.authenticate('mUc3m00RsqyRe') # => user
-
1
def authenticate(unencrypted_password)
-
BCrypt::Password.new(password_digest) == unencrypted_password && self
-
end
-
-
# Encrypts the password into the +password_digest+ attribute, only if the
-
# new password is not blank.
-
#
-
# class User < ActiveRecord::Base
-
# has_secure_password validations: false
-
# end
-
#
-
# user = User.new
-
# user.password = nil
-
# user.password_digest # => nil
-
# user.password = 'mUc3m00RsqyRe'
-
# user.password_digest # => "$2a$10$4LEA7r4YmNHtvlAvHhsYAeZmk/xeUVtMTYqwIvYY76EW5GUqDiP4."
-
1
def password=(unencrypted_password)
-
unless unencrypted_password.blank?
-
@password = unencrypted_password
-
self.password_digest = BCrypt::Password.create(unencrypted_password)
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/hash/slice'
-
-
1
module ActiveModel
-
# == Active \Model \Serialization
-
#
-
# Provides a basic serialization to a serializable_hash for your object.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# include ActiveModel::Serialization
-
#
-
# attr_accessor :name
-
#
-
# def attributes
-
# {'name' => nil}
-
# end
-
# end
-
#
-
# Which would provide you with:
-
#
-
# person = Person.new
-
# person.serializable_hash # => {"name"=>nil}
-
# person.name = "Bob"
-
# person.serializable_hash # => {"name"=>"Bob"}
-
#
-
# You need to declare an attributes hash which contains the attributes you
-
# want to serialize. Attributes must be strings, not symbols. When called,
-
# serializable hash will use instance methods that match the name of the
-
# attributes hash's keys. In order to override this behavior, take a look at
-
# the private method +read_attribute_for_serialization+.
-
#
-
# Most of the time though, you will want to include the JSON or XML
-
# serializations. Both of these modules automatically include the
-
# <tt>ActiveModel::Serialization</tt> module, so there is no need to
-
# explicitly include it.
-
#
-
# A minimal implementation including XML and JSON would be:
-
#
-
# class Person
-
# include ActiveModel::Serializers::JSON
-
# include ActiveModel::Serializers::Xml
-
#
-
# attr_accessor :name
-
#
-
# def attributes
-
# {'name' => nil}
-
# end
-
# end
-
#
-
# Which would provide you with:
-
#
-
# person = Person.new
-
# person.serializable_hash # => {"name"=>nil}
-
# person.as_json # => {"name"=>nil}
-
# person.to_json # => "{\"name\":null}"
-
# person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
-
#
-
# person.name = "Bob"
-
# person.serializable_hash # => {"name"=>"Bob"}
-
# person.as_json # => {"name"=>"Bob"}
-
# person.to_json # => "{\"name\":\"Bob\"}"
-
# person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
-
#
-
# Valid options are <tt>:only</tt>, <tt>:except</tt>, <tt>:methods</tt> and
-
# <tt>:include</tt>. The following are all valid examples:
-
#
-
# person.serializable_hash(only: 'name')
-
# person.serializable_hash(include: :address)
-
# person.serializable_hash(include: { address: { only: 'city' }})
-
1
module Serialization
-
# Returns a serialized hash of your object.
-
#
-
# class Person
-
# include ActiveModel::Serialization
-
#
-
# attr_accessor :name, :age
-
#
-
# def attributes
-
# {'name' => nil, 'age' => nil}
-
# end
-
#
-
# def capitalized_name
-
# name.capitalize
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = 'bob'
-
# person.age = 22
-
# person.serializable_hash # => {"name"=>"bob", "age"=>22}
-
# person.serializable_hash(only: :name) # => {"name"=>"bob"}
-
# person.serializable_hash(except: :name) # => {"age"=>22}
-
# person.serializable_hash(methods: :capitalized_name)
-
# # => {"name"=>"bob", "age"=>22, "capitalized_name"=>"Bob"}
-
1
def serializable_hash(options = nil)
-
options ||= {}
-
-
attribute_names = attributes.keys
-
if only = options[:only]
-
attribute_names &= Array(only).map(&:to_s)
-
elsif except = options[:except]
-
attribute_names -= Array(except).map(&:to_s)
-
end
-
-
hash = {}
-
attribute_names.each { |n| hash[n] = read_attribute_for_serialization(n) }
-
-
Array(options[:methods]).each { |m| hash[m.to_s] = send(m) if respond_to?(m) }
-
-
serializable_add_includes(options) do |association, records, opts|
-
hash[association.to_s] = if records.respond_to?(:to_ary)
-
records.to_ary.map { |a| a.serializable_hash(opts) }
-
else
-
records.serializable_hash(opts)
-
end
-
end
-
-
hash
-
end
-
-
1
private
-
-
# Hook method defining how an attribute value should be retrieved for
-
# serialization. By default this is assumed to be an instance named after
-
# the attribute. Override this method in subclasses should you need to
-
# retrieve the value for a given attribute differently:
-
#
-
# class MyClass
-
# include ActiveModel::Validations
-
#
-
# def initialize(data = {})
-
# @data = data
-
# end
-
#
-
# def read_attribute_for_serialization(key)
-
# @data[key]
-
# end
-
# end
-
1
alias :read_attribute_for_serialization :send
-
-
# Add associations specified via the <tt>:include</tt> option.
-
#
-
# Expects a block that takes as arguments:
-
# +association+ - name of the association
-
# +records+ - the association record(s) to be serialized
-
# +opts+ - options for the association records
-
1
def serializable_add_includes(options = {}) #:nodoc:
-
return unless includes = options[:include]
-
-
unless includes.is_a?(Hash)
-
includes = Hash[Array(includes).map { |n| n.is_a?(Hash) ? n.to_a.first : [n, {}] }]
-
end
-
-
includes.each do |association, opts|
-
if records = send(association)
-
yield association, records, opts
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/json'
-
-
1
module ActiveModel
-
1
module Serializers
-
# == Active Model JSON Serializer
-
1
module JSON
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::Serialization
-
-
1
included do
-
1
extend ActiveModel::Naming
-
-
1
class_attribute :include_root_in_json
-
1
self.include_root_in_json = false
-
end
-
-
# Returns a hash representing the model. Some configuration can be
-
# passed through +options+.
-
#
-
# The option <tt>include_root_in_json</tt> controls the top-level behavior
-
# of +as_json+. If +true+, +as_json+ will emit a single root node named
-
# after the object's type. The default value for <tt>include_root_in_json</tt>
-
# option is +false+.
-
#
-
# user = User.find(1)
-
# user.as_json
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true}
-
#
-
# ActiveRecord::Base.include_root_in_json = true
-
#
-
# user.as_json
-
# # => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true } }
-
#
-
# This behavior can also be achieved by setting the <tt>:root</tt> option
-
# to +true+ as in:
-
#
-
# user = User.find(1)
-
# user.as_json(root: true)
-
# # => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true } }
-
#
-
# Without any +options+, the returned Hash will include all the model's
-
# attributes.
-
#
-
# user = User.find(1)
-
# user.as_json
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true}
-
#
-
# The <tt>:only</tt> and <tt>:except</tt> options can be used to limit
-
# the attributes included, and work similar to the +attributes+ method.
-
#
-
# user.as_json(only: [:id, :name])
-
# # => { "id" => 1, "name" => "Konata Izumi" }
-
#
-
# user.as_json(except: [:id, :created_at, :age])
-
# # => { "name" => "Konata Izumi", "awesome" => true }
-
#
-
# To include the result of some method calls on the model use <tt>:methods</tt>:
-
#
-
# user.as_json(methods: :permalink)
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true,
-
# # "permalink" => "1-konata-izumi" }
-
#
-
# To include associations use <tt>:include</tt>:
-
#
-
# user.as_json(include: :posts)
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true,
-
# # "posts" => [ { "id" => 1, "author_id" => 1, "title" => "Welcome to the weblog" },
-
# # { "id" => 2, "author_id" => 1, "title" => "So I was thinking" } ] }
-
#
-
# Second level and higher order associations work as well:
-
#
-
# user.as_json(include: { posts: {
-
# include: { comments: {
-
# only: :body } },
-
# only: :title } })
-
# # => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
-
# # "created_at" => "2006/08/01", "awesome" => true,
-
# # "posts" => [ { "comments" => [ { "body" => "1st post!" }, { "body" => "Second!" } ],
-
# # "title" => "Welcome to the weblog" },
-
# # { "comments" => [ { "body" => "Don't think too hard" } ],
-
# # "title" => "So I was thinking" } ] }
-
1
def as_json(options = nil)
-
root = if options && options.key?(:root)
-
options[:root]
-
else
-
include_root_in_json
-
end
-
-
if root
-
root = self.class.model_name.element if root == true
-
{ root => serializable_hash(options) }
-
else
-
serializable_hash(options)
-
end
-
end
-
-
# Sets the model +attributes+ from a JSON string. Returns +self+.
-
#
-
# class Person
-
# include ActiveModel::Serializers::JSON
-
#
-
# attr_accessor :name, :age, :awesome
-
#
-
# def attributes=(hash)
-
# hash.each do |key, value|
-
# instance_variable_set("@#{key}", value)
-
# end
-
# end
-
#
-
# def attributes
-
# instance_values
-
# end
-
# end
-
#
-
# json = { name: 'bob', age: 22, awesome:true }.to_json
-
# person = Person.new
-
# person.from_json(json) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
-
# person.name # => "bob"
-
# person.age # => 22
-
# person.awesome # => true
-
#
-
# The default value for +include_root+ is +false+. You can change it to
-
# +true+ if the given JSON string includes a single root node.
-
#
-
# json = { person: { name: 'bob', age: 22, awesome:true } }.to_json
-
# person = Person.new
-
# person.from_json(json) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
-
# person.name # => "bob"
-
# person.age # => 22
-
# person.awesome # => true
-
1
def from_json(json, include_root=include_root_in_json)
-
hash = ActiveSupport::JSON.decode(json)
-
hash = hash.values.first if include_root
-
self.attributes = hash
-
self
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/class/attribute_accessors'
-
1
require 'active_support/core_ext/array/conversions'
-
1
require 'active_support/core_ext/hash/conversions'
-
1
require 'active_support/core_ext/hash/slice'
-
-
1
module ActiveModel
-
1
module Serializers
-
# == Active Model XML Serializer
-
1
module Xml
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::Serialization
-
-
1
included do
-
1
extend ActiveModel::Naming
-
end
-
-
1
class Serializer #:nodoc:
-
1
class Attribute #:nodoc:
-
1
attr_reader :name, :value, :type
-
-
1
def initialize(name, serializable, value)
-
@name, @serializable = name, serializable
-
value = value.in_time_zone if value.respond_to?(:in_time_zone)
-
@value = value
-
@type = compute_type
-
end
-
-
1
def decorations
-
decorations = {}
-
decorations[:encoding] = 'base64' if type == :binary
-
decorations[:type] = (type == :string) ? nil : type
-
decorations[:nil] = true if value.nil?
-
decorations
-
end
-
-
1
protected
-
-
1
def compute_type
-
return if value.nil?
-
type = ActiveSupport::XmlMini::TYPE_NAMES[value.class.name]
-
type ||= :string if value.respond_to?(:to_str)
-
type ||= :yaml
-
type
-
end
-
end
-
-
1
class MethodAttribute < Attribute #:nodoc:
-
end
-
-
1
attr_reader :options
-
-
1
def initialize(serializable, options = nil)
-
@serializable = serializable
-
@options = options ? options.dup : {}
-
end
-
-
1
def serializable_hash
-
@serializable.serializable_hash(@options.except(:include))
-
end
-
-
1
def serializable_collection
-
methods = Array(options[:methods]).map(&:to_s)
-
serializable_hash.map do |name, value|
-
name = name.to_s
-
if methods.include?(name)
-
self.class::MethodAttribute.new(name, @serializable, value)
-
else
-
self.class::Attribute.new(name, @serializable, value)
-
end
-
end
-
end
-
-
1
def serialize
-
require 'builder' unless defined? ::Builder
-
-
options[:indent] ||= 2
-
options[:builder] ||= ::Builder::XmlMarkup.new(:indent => options[:indent])
-
-
@builder = options[:builder]
-
@builder.instruct! unless options[:skip_instruct]
-
-
root = (options[:root] || @serializable.class.model_name.element).to_s
-
root = ActiveSupport::XmlMini.rename_key(root, options)
-
-
args = [root]
-
args << {:xmlns => options[:namespace]} if options[:namespace]
-
args << {:type => options[:type]} if options[:type] && !options[:skip_types]
-
-
@builder.tag!(*args) do
-
add_attributes_and_methods
-
add_includes
-
add_extra_behavior
-
add_procs
-
yield @builder if block_given?
-
end
-
end
-
-
1
private
-
-
1
def add_extra_behavior
-
end
-
-
1
def add_attributes_and_methods
-
serializable_collection.each do |attribute|
-
key = ActiveSupport::XmlMini.rename_key(attribute.name, options)
-
ActiveSupport::XmlMini.to_tag(key, attribute.value,
-
options.merge(attribute.decorations))
-
end
-
end
-
-
1
def add_includes
-
@serializable.send(:serializable_add_includes, options) do |association, records, opts|
-
add_associations(association, records, opts)
-
end
-
end
-
-
# TODO: This can likely be cleaned up to simple use ActiveSupport::XmlMini.to_tag as well.
-
1
def add_associations(association, records, opts)
-
merged_options = opts.merge(options.slice(:builder, :indent))
-
merged_options[:skip_instruct] = true
-
-
[:skip_types, :dasherize, :camelize].each do |key|
-
merged_options[key] = options[key] if merged_options[key].nil? && !options[key].nil?
-
end
-
-
if records.respond_to?(:to_ary)
-
records = records.to_ary
-
-
tag = ActiveSupport::XmlMini.rename_key(association.to_s, options)
-
type = options[:skip_types] ? { } : {:type => "array"}
-
association_name = association.to_s.singularize
-
merged_options[:root] = association_name
-
-
if records.empty?
-
@builder.tag!(tag, type)
-
else
-
@builder.tag!(tag, type) do
-
records.each do |record|
-
if options[:skip_types]
-
record_type = {}
-
else
-
record_class = (record.class.to_s.underscore == association_name) ? nil : record.class.name
-
record_type = {:type => record_class}
-
end
-
-
record.to_xml merged_options.merge(record_type)
-
end
-
end
-
end
-
else
-
merged_options[:root] = association.to_s
-
records.to_xml(merged_options)
-
end
-
end
-
-
1
def add_procs
-
if procs = options.delete(:procs)
-
Array(procs).each do |proc|
-
if proc.arity == 1
-
proc.call(options)
-
else
-
proc.call(options, @serializable)
-
end
-
end
-
end
-
end
-
end
-
-
# Returns XML representing the model. Configuration can be
-
# passed through +options+.
-
#
-
# Without any +options+, the returned XML string will include all the
-
# model's attributes.
-
#
-
# user = User.find(1)
-
# user.to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <user>
-
# <id type="integer">1</id>
-
# <name>David</name>
-
# <age type="integer">16</age>
-
# <created-at type="dateTime">2011-01-30T22:29:23Z</created-at>
-
# </user>
-
#
-
# The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the
-
# attributes included, and work similar to the +attributes+ method.
-
#
-
# To include the result of some method calls on the model use <tt>:methods</tt>.
-
#
-
# To include associations use <tt>:include</tt>.
-
#
-
# For further documentation, see <tt>ActiveRecord::Serialization#to_xml</tt>
-
1
def to_xml(options = {}, &block)
-
Serializer.new(self, options).serialize(&block)
-
end
-
-
# Sets the model +attributes+ from a JSON string. Returns +self+.
-
#
-
# class Person
-
# include ActiveModel::Serializers::Xml
-
#
-
# attr_accessor :name, :age, :awesome
-
#
-
# def attributes=(hash)
-
# hash.each do |key, value|
-
# instance_variable_set("@#{key}", value)
-
# end
-
# end
-
#
-
# def attributes
-
# instance_values
-
# end
-
# end
-
#
-
# xml = { name: 'bob', age: 22, awesome:true }.to_xml
-
# person = Person.new
-
# person.from_xml(xml) # => #<Person:0x007fec5e3b3c40 @age=22, @awesome=true, @name="bob">
-
# person.name # => "bob"
-
# person.age # => 22
-
# person.awesome # => true
-
1
def from_xml(xml)
-
self.attributes = Hash.from_xml(xml).values.first
-
self
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
-
# == Active \Model \Translation
-
#
-
# Provides integration between your object and the Rails internationalization
-
# (i18n) framework.
-
#
-
# A minimal implementation could be:
-
#
-
# class TranslatedPerson
-
# extend ActiveModel::Translation
-
# end
-
#
-
# TranslatedPerson.human_attribute_name('my_attribute')
-
# # => "My attribute"
-
#
-
# This also provides the required class methods for hooking into the
-
# Rails internationalization API, including being able to define a
-
# class based +i18n_scope+ and +lookup_ancestors+ to find translations in
-
# parent classes.
-
1
module Translation
-
1
include ActiveModel::Naming
-
-
# Returns the +i18n_scope+ for the class. Overwrite if you want custom lookup.
-
1
def i18n_scope
-
:activemodel
-
end
-
-
# When localizing a string, it goes through the lookup returned by this
-
# method, which is used in ActiveModel::Name#human,
-
# ActiveModel::Errors#full_messages and
-
# ActiveModel::Translation#human_attribute_name.
-
1
def lookup_ancestors
-
self.ancestors.select { |x| x.respond_to?(:model_name) }
-
end
-
-
# Transforms attribute names into a more human format, such as "First name"
-
# instead of "first_name".
-
#
-
# Person.human_attribute_name("first_name") # => "First name"
-
#
-
# Specify +options+ with additional translating options.
-
1
def human_attribute_name(attribute, options = {})
-
options = { :count => 1 }.merge!(options)
-
parts = attribute.to_s.split(".")
-
attribute = parts.pop
-
namespace = parts.join("/") unless parts.empty?
-
attributes_scope = "#{self.i18n_scope}.attributes"
-
-
if namespace
-
defaults = lookup_ancestors.map do |klass|
-
:"#{attributes_scope}.#{klass.model_name.i18n_key}/#{namespace}.#{attribute}"
-
end
-
defaults << :"#{attributes_scope}.#{namespace}.#{attribute}"
-
else
-
defaults = lookup_ancestors.map do |klass|
-
:"#{attributes_scope}.#{klass.model_name.i18n_key}.#{attribute}"
-
end
-
end
-
-
defaults << :"attributes.#{attribute}"
-
defaults << options.delete(:default) if options[:default]
-
defaults << attribute.humanize
-
-
options[:default] = defaults
-
I18n.translate(defaults.shift, options)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_model/errors'
-
1
require 'active_model/validations/callbacks'
-
1
require 'active_model/validator'
-
-
1
module ActiveModel
-
-
# == Active \Model Validations
-
#
-
# Provides a full validation framework to your objects.
-
#
-
# A minimal implementation could be:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :first_name, :last_name
-
#
-
# validates_each :first_name, :last_name do |record, attr, value|
-
# record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
-
# end
-
# end
-
#
-
# Which provides you with the full standard validation stack that you
-
# know from Active Record:
-
#
-
# person = Person.new
-
# person.valid? # => true
-
# person.invalid? # => false
-
#
-
# person.first_name = 'zoolander'
-
# person.valid? # => false
-
# person.invalid? # => true
-
# person.errors.messages # => {first_name:["starts with z."]}
-
#
-
# Note that <tt>ActiveModel::Validations</tt> automatically adds an +errors+
-
# method to your instances initialized with a new <tt>ActiveModel::Errors</tt>
-
# object, so there is no need for you to do this manually.
-
1
module Validations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
extend ActiveModel::Callbacks
-
1
extend ActiveModel::Translation
-
-
1
extend HelperMethods
-
1
include HelperMethods
-
-
1
attr_accessor :validation_context
-
1
define_callbacks :validate, :scope => :name
-
-
1
class_attribute :_validators
-
1
self._validators = Hash.new { |h,k| h[k] = [] }
-
end
-
-
1
module ClassMethods
-
# Validates each attribute against a block.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :first_name, :last_name
-
#
-
# validates_each :first_name, :last_name, allow_blank: true do |record, attr, value|
-
# record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
-
# end
-
# end
-
#
-
# Options:
-
# * <tt>:on</tt> - Specifies the context where this validation is active
-
# (e.g. <tt>on: :create</tt> or <tt>on: :custom_validation_context</tt>)
-
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
-
# * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or +false+
-
# value.
-
1
def validates_each(*attr_names, &block)
-
validates_with BlockValidator, _merge_attributes(attr_names), &block
-
end
-
-
# Adds a validation method or block to the class. This is useful when
-
# overriding the +validate+ instance method becomes too unwieldy and
-
# you're looking for more descriptive declaration of your validations.
-
#
-
# This can be done with a symbol pointing to a method:
-
#
-
# class Comment
-
# include ActiveModel::Validations
-
#
-
# validate :must_be_friends
-
#
-
# def must_be_friends
-
# errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
-
# end
-
# end
-
#
-
# With a block which is passed with the current record to be validated:
-
#
-
# class Comment
-
# include ActiveModel::Validations
-
#
-
# validate do |comment|
-
# comment.must_be_friends
-
# end
-
#
-
# def must_be_friends
-
# errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
-
# end
-
# end
-
#
-
# Or with a block where self points to the current record to be validated:
-
#
-
# class Comment
-
# include ActiveModel::Validations
-
#
-
# validate do
-
# errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
-
# end
-
# end
-
#
-
# Options:
-
# * <tt>:on</tt> - Specifies the context where this validation is active
-
# (e.g. <tt>on: :create</tt> or <tt>on: :custom_validation_context</tt>)
-
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
-
# * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or +false+
-
# value.
-
1
def validate(*args, &block)
-
options = args.extract_options!
-
if options.key?(:on)
-
options = options.dup
-
options[:if] = Array(options[:if])
-
options[:if].unshift("validation_context == :#{options[:on]}")
-
end
-
args << options
-
set_callback(:validate, *args, &block)
-
end
-
-
# List all validators that are being used to validate the model using
-
# +validates_with+ method.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# validates_with MyValidator
-
# validates_with OtherValidator, on: :create
-
# validates_with StrictValidator, strict: true
-
# end
-
#
-
# Person.validators
-
# # => [
-
# # #<MyValidator:0x007fbff403e808 @options={}>,
-
# # #<OtherValidator:0x007fbff403d930 @options={on: :create}>,
-
# # #<StrictValidator:0x007fbff3204a30 @options={strict:true}>
-
# # ]
-
1
def validators
-
_validators.values.flatten.uniq
-
end
-
-
# List all validators that are being used to validate a specific attribute.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name , :age
-
#
-
# validates_presence_of :name
-
# validates_inclusion_of :age, in: 0..99
-
# end
-
#
-
# Person.validators_on(:name)
-
# # => [
-
# # #<ActiveModel::Validations::PresenceValidator:0x007fe604914e60 @attributes=[:name], @options={}>,
-
# # #<ActiveModel::Validations::InclusionValidator:0x007fe603bb8780 @attributes=[:age], @options={in:0..99}>
-
# # ]
-
1
def validators_on(*attributes)
-
attributes.flat_map do |attribute|
-
_validators[attribute.to_sym]
-
end
-
end
-
-
# Returns +true+ if +attribute+ is an attribute method, +false+ otherwise.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# end
-
#
-
# User.attribute_method?(:name) # => true
-
# User.attribute_method?(:age) # => false
-
1
def attribute_method?(attribute)
-
method_defined?(attribute)
-
end
-
-
# Copy validators on inheritance.
-
1
def inherited(base) #:nodoc:
-
1
dup = _validators.dup
-
1
base._validators = dup.each { |k, v| dup[k] = v.dup }
-
1
super
-
end
-
end
-
-
# Clean the +Errors+ object if instance is duped.
-
1
def initialize_dup(other) #:nodoc:
-
@errors = nil
-
super
-
end
-
-
# Returns the +Errors+ object that holds all information about attribute
-
# error messages.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name
-
# end
-
#
-
# person = Person.new
-
# person.valid? # => false
-
# person.errors # => #<ActiveModel::Errors:0x007fe603816640 @messages={name:["can't be blank"]}>
-
1
def errors
-
@errors ||= Errors.new(self)
-
end
-
-
# Runs all the specified validations and returns +true+ if no errors were
-
# added otherwise +false+.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name
-
# end
-
#
-
# person = Person.new
-
# person.name = ''
-
# person.valid? # => false
-
# person.name = 'david'
-
# person.valid? # => true
-
#
-
# Context can optionally be supplied to define which callbacks to test
-
# against (the context is defined on the validations using <tt>:on</tt>).
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name, on: :new
-
# end
-
#
-
# person = Person.new
-
# person.valid? # => true
-
# person.valid?(:new) # => false
-
1
def valid?(context = nil)
-
current_context, self.validation_context = validation_context, context
-
errors.clear
-
run_validations!
-
ensure
-
self.validation_context = current_context
-
end
-
-
# Performs the opposite of <tt>valid?</tt>. Returns +true+ if errors were
-
# added, +false+ otherwise.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name
-
# end
-
#
-
# person = Person.new
-
# person.name = ''
-
# person.invalid? # => true
-
# person.name = 'david'
-
# person.invalid? # => false
-
#
-
# Context can optionally be supplied to define which callbacks to test
-
# against (the context is defined on the validations using <tt>:on</tt>).
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates_presence_of :name, on: :new
-
# end
-
#
-
# person = Person.new
-
# person.invalid? # => false
-
# person.invalid?(:new) # => true
-
1
def invalid?(context = nil)
-
!valid?(context)
-
end
-
-
# Hook method defining how an attribute value should be retrieved. By default
-
# this is assumed to be an instance named after the attribute. Override this
-
# method in subclasses should you need to retrieve the value for a given
-
# attribute differently:
-
#
-
# class MyClass
-
# include ActiveModel::Validations
-
#
-
# def initialize(data = {})
-
# @data = data
-
# end
-
#
-
# def read_attribute_for_validation(key)
-
# @data[key]
-
# end
-
# end
-
1
alias :read_attribute_for_validation :send
-
-
1
protected
-
-
1
def run_validations! #:nodoc:
-
run_callbacks :validate
-
errors.empty?
-
end
-
end
-
end
-
-
1
Dir[File.dirname(__FILE__) + "/validations/*.rb"].sort.each do |path|
-
12
filename = File.basename(path)
-
12
require "active_model/validations/#{filename}"
-
end
-
1
module ActiveModel
-
-
1
module Validations
-
1
class AcceptanceValidator < EachValidator # :nodoc:
-
1
def initialize(options)
-
super({ :allow_nil => true, :accept => "1" }.merge!(options))
-
end
-
-
1
def validate_each(record, attribute, value)
-
unless value == options[:accept]
-
record.errors.add(attribute, :accepted, options.except(:accept, :allow_nil))
-
end
-
end
-
-
1
def setup(klass)
-
attr_readers = attributes.reject { |name| klass.attribute_method?(name) }
-
attr_writers = attributes.reject { |name| klass.attribute_method?("#{name}=") }
-
klass.send(:attr_reader, *attr_readers)
-
klass.send(:attr_writer, *attr_writers)
-
end
-
end
-
-
1
module HelperMethods
-
# Encapsulates the pattern of wanting to validate the acceptance of a
-
# terms of service check box (or similar agreement).
-
#
-
# class Person < ActiveRecord::Base
-
# validates_acceptance_of :terms_of_service
-
# validates_acceptance_of :eula, message: 'must be abided'
-
# end
-
#
-
# If the database column does not exist, the +terms_of_service+ attribute
-
# is entirely virtual. This check is performed only if +terms_of_service+
-
# is not +nil+ and by default on save.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "must be
-
# accepted").
-
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default
-
# is +true+).
-
# * <tt>:accept</tt> - Specifies value that is considered accepted.
-
# The default value is a string "1", which makes it easy to relate to
-
# an HTML checkbox. This should be set to +true+ if you are validating
-
# a database column, since the attribute is typecast from "1" to +true+
-
# before validation.
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+ and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_acceptance_of(*attr_names)
-
validates_with AcceptanceValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
require 'active_support/callbacks'
-
-
1
module ActiveModel
-
1
module Validations
-
# == Active \Model Validation Callbacks
-
#
-
# Provides an interface for any class to have +before_validation+ and
-
# +after_validation+ callbacks.
-
#
-
# First, include ActiveModel::Validations::Callbacks from the class you are
-
# creating:
-
#
-
# class MyModel
-
# include ActiveModel::Validations::Callbacks
-
#
-
# before_validation :do_stuff_before_validation
-
# after_validation :do_stuff_after_validation
-
# end
-
#
-
# Like other <tt>before_*</tt> callbacks if +before_validation+ returns
-
# +false+ then <tt>valid?</tt> will not be called.
-
1
module Callbacks
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
include ActiveSupport::Callbacks
-
1
define_callbacks :validation, :terminator => "result == false", :skip_after_callbacks_if_terminated => true, :scope => [:kind, :name]
-
end
-
-
1
module ClassMethods
-
# Defines a callback that will get called right before validation
-
# happens.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# include ActiveModel::Validations::Callbacks
-
#
-
# attr_accessor :name
-
#
-
# validates_length_of :name, maximum: 6
-
#
-
# before_validation :remove_whitespaces
-
#
-
# private
-
#
-
# def remove_whitespaces
-
# name.strip!
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = ' bob '
-
# person.valid? # => true
-
# person.name # => "bob"
-
1
def before_validation(*args, &block)
-
options = args.last
-
if options.is_a?(Hash) && options[:on]
-
options[:if] = Array(options[:if])
-
options[:on] = Array(options[:on])
-
options[:if].unshift("#{options[:on]}.include? self.validation_context")
-
end
-
set_callback(:validation, :before, *args, &block)
-
end
-
-
# Defines a callback that will get called right after validation
-
# happens.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# include ActiveModel::Validations::Callbacks
-
#
-
# attr_accessor :name, :status
-
#
-
# validates_presence_of :name
-
#
-
# after_validation :set_status
-
#
-
# private
-
#
-
# def set_status
-
# self.status = errors.empty?
-
# end
-
# end
-
#
-
# person = Person.new
-
# person.name = ''
-
# person.valid? # => false
-
# person.status # => false
-
# person.name = 'bob'
-
# person.valid? # => true
-
# person.status # => true
-
1
def after_validation(*args, &block)
-
options = args.extract_options!
-
options[:prepend] = true
-
options[:if] = Array(options[:if])
-
if options[:on]
-
options[:on] = Array(options[:on])
-
options[:if].unshift("#{options[:on]}.include? self.validation_context")
-
end
-
set_callback(:validation, :after, *(args << options), &block)
-
end
-
end
-
-
1
protected
-
-
# Overwrite run validations to include callbacks.
-
1
def run_validations! #:nodoc:
-
run_callbacks(:validation) { super }
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/range'
-
-
1
module ActiveModel
-
1
module Validations
-
1
module Clusivity #:nodoc:
-
1
ERROR_MESSAGE = "An object with the method #include? or a proc, lambda or symbol is required, " <<
-
"and must be supplied as the :in (or :within) option of the configuration hash"
-
-
1
def check_validity!
-
unless delimiter.respond_to?(:include?) || delimiter.respond_to?(:call) || delimiter.respond_to?(:to_sym)
-
raise ArgumentError, ERROR_MESSAGE
-
end
-
end
-
-
1
private
-
-
1
def include?(record, value)
-
exclusions = if delimiter.respond_to?(:call)
-
delimiter.call(record)
-
elsif delimiter.respond_to?(:to_sym)
-
record.send(delimiter)
-
else
-
delimiter
-
end
-
-
exclusions.send(inclusion_method(exclusions), value)
-
end
-
-
1
def delimiter
-
@delimiter ||= options[:in] || options[:within]
-
end
-
-
# In Ruby 1.9 <tt>Range#include?</tt> on non-numeric ranges checks all possible values in the
-
# range for equality, so it may be slow for large ranges. The new <tt>Range#cover?</tt>
-
# uses the previous logic of comparing a value with the range endpoints.
-
1
def inclusion_method(enumerable)
-
enumerable.is_a?(Range) ? :cover? : :include?
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
-
1
module Validations
-
1
class ConfirmationValidator < EachValidator # :nodoc:
-
1
def validate_each(record, attribute, value)
-
if (confirmed = record.send("#{attribute}_confirmation")) && (value != confirmed)
-
human_attribute_name = record.class.human_attribute_name(attribute)
-
record.errors.add(:"#{attribute}_confirmation", :confirmation, options.merge(:attribute => human_attribute_name))
-
end
-
end
-
-
1
def setup(klass)
-
klass.send(:attr_accessor, *attributes.map do |attribute|
-
:"#{attribute}_confirmation" unless klass.method_defined?(:"#{attribute}_confirmation")
-
end.compact)
-
end
-
end
-
-
1
module HelperMethods
-
# Encapsulates the pattern of wanting to validate a password or email
-
# address field with a confirmation.
-
#
-
# Model:
-
# class Person < ActiveRecord::Base
-
# validates_confirmation_of :user_name, :password
-
# validates_confirmation_of :email_address,
-
# message: 'should match confirmation'
-
# end
-
#
-
# View:
-
# <%= password_field "person", "password" %>
-
# <%= password_field "person", "password_confirmation" %>
-
#
-
# The added +password_confirmation+ attribute is virtual; it exists only
-
# as an in-memory attribute for validating the password. To achieve this,
-
# the validation adds accessors to the model for the confirmation
-
# attribute.
-
#
-
# NOTE: This check is performed only if +password_confirmation+ is not
-
# +nil+. To require confirmation, make sure to add a presence check for
-
# the confirmation attribute:
-
#
-
# validates_presence_of :password_confirmation, if: :password_changed?
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "doesn't match
-
# confirmation").
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+ and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_confirmation_of(*attr_names)
-
validates_with ConfirmationValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
require "active_model/validations/clusivity"
-
-
1
module ActiveModel
-
-
1
module Validations
-
1
class ExclusionValidator < EachValidator # :nodoc:
-
1
include Clusivity
-
-
1
def validate_each(record, attribute, value)
-
if include?(record, value)
-
record.errors.add(attribute, :exclusion, options.except(:in, :within).merge!(:value => value))
-
end
-
end
-
end
-
-
1
module HelperMethods
-
# Validates that the value of the specified attribute is not in a
-
# particular enumerable object.
-
#
-
# class Person < ActiveRecord::Base
-
# validates_exclusion_of :username, in: %w( admin superuser ), message: "You don't belong here"
-
# validates_exclusion_of :age, in: 30..60, message: 'This site is only for under 30 and over 60'
-
# validates_exclusion_of :format, in: %w( mov avi ), message: "extension %{value} is not allowed"
-
# validates_exclusion_of :password, in: ->(person) { [person.username, person.first_name] },
-
# message: 'should not be the same as your username or first name'
-
# validates_exclusion_of :karma, in: :reserved_karmas
-
# end
-
#
-
# Configuration options:
-
# * <tt>:in</tt> - An enumerable object of items that the value shouldn't
-
# be part of. This can be supplied as a proc, lambda or symbol which returns an
-
# enumerable. If the enumerable is a range the test is performed with
-
# * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
-
# <tt>Range#cover?</tt>, otherwise with <tt>include?</tt>.
-
# * <tt>:message</tt> - Specifies a custom error message (default is: "is
-
# reserved").
-
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the
-
# attribute is +nil+ (default is +false+).
-
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the
-
# attribute is blank(default is +false+).
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+ and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_exclusion_of(*attr_names)
-
validates_with ExclusionValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
-
1
module Validations
-
1
class FormatValidator < EachValidator # :nodoc:
-
1
def validate_each(record, attribute, value)
-
if options[:with]
-
regexp = option_call(record, :with)
-
record_error(record, attribute, :with, value) if value.to_s !~ regexp
-
elsif options[:without]
-
regexp = option_call(record, :without)
-
record_error(record, attribute, :without, value) if value.to_s =~ regexp
-
end
-
end
-
-
1
def check_validity!
-
unless options.include?(:with) ^ options.include?(:without) # ^ == xor, or "exclusive or"
-
raise ArgumentError, "Either :with or :without must be supplied (but not both)"
-
end
-
-
check_options_validity(options, :with)
-
check_options_validity(options, :without)
-
end
-
-
1
private
-
-
1
def option_call(record, name)
-
option = options[name]
-
option.respond_to?(:call) ? option.call(record) : option
-
end
-
-
1
def record_error(record, attribute, name, value)
-
record.errors.add(attribute, :invalid, options.except(name).merge!(:value => value))
-
end
-
-
1
def regexp_using_multiline_anchors?(regexp)
-
regexp.source.start_with?("^") ||
-
(regexp.source.end_with?("$") && !regexp.source.end_with?("\\$"))
-
end
-
-
1
def check_options_validity(options, name)
-
option = options[name]
-
if option && !option.is_a?(Regexp) && !option.respond_to?(:call)
-
raise ArgumentError, "A regular expression or a proc or lambda must be supplied as :#{name}"
-
elsif option && option.is_a?(Regexp) &&
-
regexp_using_multiline_anchors?(option) && options[:multiline] != true
-
raise ArgumentError, "The provided regular expression is using multiline anchors (^ or $), " \
-
"which may present a security risk. Did you mean to use \\A and \\z, or forgot to add the " \
-
":multiline => true option?"
-
end
-
end
-
end
-
-
1
module HelperMethods
-
# Validates whether the value of the specified attribute is of the correct
-
# form, going by the regular expression provided.You can require that the
-
# attribute matches the regular expression:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create
-
# end
-
#
-
# Alternatively, you can require that the specified attribute does _not_
-
# match the regular expression:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_format_of :email, without: /NOSPAM/
-
# end
-
#
-
# You can also provide a proc or lambda which will determine the regular
-
# expression that will be used to validate the attribute.
-
#
-
# class Person < ActiveRecord::Base
-
# # Admin can have number as a first letter in their screen name
-
# validates_format_of :screen_name,
-
# with: ->(person) { person.admin? ? /\A[a-z0-9][a-z0-9_\-]*\z/i : /\A[a-z][a-z0-9_\-]*\z/i }
-
# end
-
#
-
# Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the
-
# string, <tt>^</tt> and <tt>$</tt> match the start/end of a line.
-
#
-
# Due to frequent misuse of <tt>^</tt> and <tt>$</tt>, you need to pass
-
# the <tt>multiline: true</tt> option in case you use any of these two
-
# anchors in the provided regular expression. In most cases, you should be
-
# using <tt>\A</tt> and <tt>\z</tt>.
-
#
-
# You must pass either <tt>:with</tt> or <tt>:without</tt> as an option.
-
# In addition, both must be a regular expression or a proc or lambda, or
-
# else an exception will be raised.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "is invalid").
-
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the
-
# attribute is +nil+ (default is +false+).
-
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the
-
# attribute is blank (default is +false+).
-
# * <tt>:with</tt> - Regular expression that if the attribute matches will
-
# result in a successful validation. This can be provided as a proc or
-
# lambda returning regular expression which will be called at runtime.
-
# * <tt>:without</tt> - Regular expression that if the attribute does not
-
# match will result in a successful validation. This can be provided as
-
# a proc or lambda returning regular expression which will be called at
-
# runtime.
-
# * <tt>:multiline</tt> - Set to true if your regular expression contains
-
# anchors that match the beginning or end of lines as opposed to the
-
# beginning or end of the string. These anchors are <tt>^</tt> and <tt>$</tt>.
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+ and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_format_of(*attr_names)
-
validates_with FormatValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
require "active_model/validations/clusivity"
-
-
1
module ActiveModel
-
-
1
module Validations
-
1
class InclusionValidator < EachValidator # :nodoc:
-
1
include Clusivity
-
-
1
def validate_each(record, attribute, value)
-
unless include?(record, value)
-
record.errors.add(attribute, :inclusion, options.except(:in, :within).merge!(:value => value))
-
end
-
end
-
end
-
-
1
module HelperMethods
-
# Validates whether the value of the specified attribute is available in a
-
# particular enumerable object.
-
#
-
# class Person < ActiveRecord::Base
-
# validates_inclusion_of :gender, in: %w( m f )
-
# validates_inclusion_of :age, in: 0..99
-
# validates_inclusion_of :format, in: %w( jpg gif png ), message: "extension %{value} is not included in the list"
-
# validates_inclusion_of :states, in: ->(person) { STATES[person.country] }
-
# validates_inclusion_of :karma, in: :available_karmas
-
# end
-
#
-
# Configuration options:
-
# * <tt>:in</tt> - An enumerable object of available items. This can be
-
# supplied as a proc, lambda or symbol which returns an enumerable. If the
-
# enumerable is a range the test is performed with <tt>Range#cover?</tt>,
-
# otherwise with <tt>include?</tt>.
-
# * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
-
# * <tt>:message</tt> - Specifies a custom error message (default is: "is
-
# not included in the list").
-
# * <tt>:allow_nil</tt> - If set to +true+, skips this validation if the
-
# attribute is +nil+ (default is +false+).
-
# * <tt>:allow_blank</tt> - If set to +true+, skips this validation if the
-
# attribute is blank (default is +false+).
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+ and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_inclusion_of(*attr_names)
-
validates_with InclusionValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
-
# == Active \Model Length \Validator
-
1
module Validations
-
1
class LengthValidator < EachValidator # :nodoc:
-
1
MESSAGES = { :is => :wrong_length, :minimum => :too_short, :maximum => :too_long }.freeze
-
1
CHECKS = { :is => :==, :minimum => :>=, :maximum => :<= }.freeze
-
-
1
RESERVED_OPTIONS = [:minimum, :maximum, :within, :is, :tokenizer, :too_short, :too_long]
-
-
1
def initialize(options)
-
if range = (options.delete(:in) || options.delete(:within))
-
raise ArgumentError, ":in and :within must be a Range" unless range.is_a?(Range)
-
options[:minimum], options[:maximum] = range.min, range.max
-
end
-
-
super
-
end
-
-
1
def check_validity!
-
keys = CHECKS.keys & options.keys
-
-
if keys.empty?
-
raise ArgumentError, 'Range unspecified. Specify the :in, :within, :maximum, :minimum, or :is option.'
-
end
-
-
keys.each do |key|
-
value = options[key]
-
-
unless (value.is_a?(Integer) && value >= 0) || value == Float::INFINITY
-
raise ArgumentError, ":#{key} must be a nonnegative Integer or Infinity"
-
end
-
end
-
end
-
-
1
def validate_each(record, attribute, value)
-
value = tokenize(value)
-
value_length = value.respond_to?(:length) ? value.length : value.to_s.length
-
errors_options = options.except(*RESERVED_OPTIONS)
-
-
CHECKS.each do |key, validity_check|
-
next unless check_value = options[key]
-
next if value_length.send(validity_check, check_value)
-
-
errors_options[:count] = check_value
-
-
default_message = options[MESSAGES[key]]
-
errors_options[:message] ||= default_message if default_message
-
-
record.errors.add(attribute, MESSAGES[key], errors_options)
-
end
-
end
-
-
1
private
-
-
1
def tokenize(value)
-
if options[:tokenizer] && value.kind_of?(String)
-
options[:tokenizer].call(value)
-
end || value
-
end
-
end
-
-
1
module HelperMethods
-
-
# Validates that the specified attribute matches the length restrictions
-
# supplied. Only one option can be used at a time:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_length_of :first_name, maximum: 30
-
# validates_length_of :last_name, maximum: 30, message: "less than 30 if you don't mind"
-
# validates_length_of :fax, in: 7..32, allow_nil: true
-
# validates_length_of :phone, in: 7..32, allow_blank: true
-
# validates_length_of :user_name, within: 6..20, too_long: 'pick a shorter name', too_short: 'pick a longer name'
-
# validates_length_of :zip_code, minimum: 5, too_short: 'please enter at least 5 characters'
-
# validates_length_of :smurf_leader, is: 4, message: "papa is spelled with 4 characters... don't play me."
-
# validates_length_of :essay, minimum: 100, too_short: 'Your essay must be at least 100 words.',
-
# tokenizer: ->(str) { str.scan(/\w+/) }
-
# end
-
#
-
# Configuration options:
-
# * <tt>:minimum</tt> - The minimum size of the attribute.
-
# * <tt>:maximum</tt> - The maximum size of the attribute.
-
# * <tt>:is</tt> - The exact size of the attribute.
-
# * <tt>:within</tt> - A range specifying the minimum and maximum size of
-
# the attribute.
-
# * <tt>:in</tt> - A synonym (or alias) for <tt>:within</tt>.
-
# * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
-
# * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
-
# * <tt>:too_long</tt> - The error message if the attribute goes over the
-
# maximum (default is: "is too long (maximum is %{count} characters)").
-
# * <tt>:too_short</tt> - The error message if the attribute goes under the
-
# minimum (default is: "is too short (min is %{count} characters)").
-
# * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt>
-
# method and the attribute is the wrong size (default is: "is the wrong
-
# length (should be %{count} characters)").
-
# * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>,
-
# <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate
-
# <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
-
# * <tt>:tokenizer</tt> - Specifies how to split up the attribute string.
-
# (e.g. <tt>tokenizer: ->(str) { str.scan(/\w+/) }</tt> to count words
-
# as in above example). Defaults to <tt>->(value) { value.split(//) }</tt>
-
# which counts individual characters.
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+ and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_length_of(*attr_names)
-
validates_with LengthValidator, _merge_attributes(attr_names)
-
end
-
-
1
alias_method :validates_size_of, :validates_length_of
-
end
-
end
-
end
-
1
module ActiveModel
-
-
1
module Validations
-
1
class NumericalityValidator < EachValidator # :nodoc:
-
1
CHECKS = { :greater_than => :>, :greater_than_or_equal_to => :>=,
-
:equal_to => :==, :less_than => :<, :less_than_or_equal_to => :<=,
-
:odd => :odd?, :even => :even?, :other_than => :!= }.freeze
-
-
1
RESERVED_OPTIONS = CHECKS.keys + [:only_integer]
-
-
1
def check_validity!
-
keys = CHECKS.keys - [:odd, :even]
-
options.slice(*keys).each do |option, value|
-
next if value.is_a?(Numeric) || value.is_a?(Proc) || value.is_a?(Symbol)
-
raise ArgumentError, ":#{option} must be a number, a symbol or a proc"
-
end
-
end
-
-
1
def validate_each(record, attr_name, value)
-
before_type_cast = "#{attr_name}_before_type_cast"
-
-
raw_value = record.send(before_type_cast) if record.respond_to?(before_type_cast.to_sym)
-
raw_value ||= value
-
-
return if options[:allow_nil] && raw_value.nil?
-
-
unless value = parse_raw_value_as_a_number(raw_value)
-
record.errors.add(attr_name, :not_a_number, filtered_options(raw_value))
-
return
-
end
-
-
if options[:only_integer]
-
unless value = parse_raw_value_as_an_integer(raw_value)
-
record.errors.add(attr_name, :not_an_integer, filtered_options(raw_value))
-
return
-
end
-
end
-
-
options.slice(*CHECKS.keys).each do |option, option_value|
-
case option
-
when :odd, :even
-
unless value.to_i.send(CHECKS[option])
-
record.errors.add(attr_name, option, filtered_options(value))
-
end
-
else
-
option_value = option_value.call(record) if option_value.is_a?(Proc)
-
option_value = record.send(option_value) if option_value.is_a?(Symbol)
-
-
unless value.send(CHECKS[option], option_value)
-
record.errors.add(attr_name, option, filtered_options(value).merge(:count => option_value))
-
end
-
end
-
end
-
end
-
-
1
protected
-
-
1
def parse_raw_value_as_a_number(raw_value)
-
case raw_value
-
when /\A0[xX]/
-
nil
-
else
-
begin
-
Kernel.Float(raw_value)
-
rescue ArgumentError, TypeError
-
nil
-
end
-
end
-
end
-
-
1
def parse_raw_value_as_an_integer(raw_value)
-
raw_value.to_i if raw_value.to_s =~ /\A[+-]?\d+\Z/
-
end
-
-
1
def filtered_options(value)
-
options.except(*RESERVED_OPTIONS).merge!(:value => value)
-
end
-
end
-
-
1
module HelperMethods
-
# Validates whether the value of the specified attribute is numeric by
-
# trying to convert it to a float with Kernel.Float (if <tt>only_integer</tt>
-
# is +false+) or applying it to the regular expression <tt>/\A[\+\-]?\d+\Z/</tt>
-
# (if <tt>only_integer</tt> is set to +true+).
-
#
-
# class Person < ActiveRecord::Base
-
# validates_numericality_of :value, on: :create
-
# end
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "is not a number").
-
# * <tt>:only_integer</tt> - Specifies whether the value has to be an
-
# integer, e.g. an integral value (default is +false+).
-
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is
-
# +false+). Notice that for fixnum and float columns empty strings are
-
# converted to +nil+.
-
# * <tt>:greater_than</tt> - Specifies the value must be greater than the
-
# supplied value.
-
# * <tt>:greater_than_or_equal_to</tt> - Specifies the value must be
-
# greater than or equal the supplied value.
-
# * <tt>:equal_to</tt> - Specifies the value must be equal to the supplied
-
# value.
-
# * <tt>:less_than</tt> - Specifies the value must be less than the
-
# supplied value.
-
# * <tt>:less_than_or_equal_to</tt> - Specifies the value must be less
-
# than or equal the supplied value.
-
# * <tt>:other_than</tt> - Specifies the value must be other than the
-
# supplied value.
-
# * <tt>:odd</tt> - Specifies the value must be an odd number.
-
# * <tt>:even</tt> - Specifies the value must be an even number.
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+ and +:strict+ .
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
#
-
# The following checks can also be supplied with a proc or a symbol which
-
# corresponds to a method:
-
#
-
# * <tt>:greater_than</tt>
-
# * <tt>:greater_than_or_equal_to</tt>
-
# * <tt>:equal_to</tt>
-
# * <tt>:less_than</tt>
-
# * <tt>:less_than_or_equal_to</tt>
-
#
-
# For example:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_numericality_of :width, less_than: ->(person) { person.height }
-
# validates_numericality_of :width, greater_than: :minimum_weight
-
# end
-
1
def validates_numericality_of(*attr_names)
-
validates_with NumericalityValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
-
1
module ActiveModel
-
-
1
module Validations
-
1
class PresenceValidator < EachValidator # :nodoc:
-
1
def validate(record)
-
record.errors.add_on_blank(attributes, options)
-
end
-
end
-
-
1
module HelperMethods
-
# Validates that the specified attributes are not blank (as defined by
-
# Object#blank?). Happens by default on save.
-
#
-
# class Person < ActiveRecord::Base
-
# validates_presence_of :first_name
-
# end
-
#
-
# The first_name attribute must be in the object and it cannot be blank.
-
#
-
# If you want to validate the presence of a boolean field (where the real
-
# values are +true+ and +false+), you will want to use
-
# <tt>validates_inclusion_of :field_name, in: [true, false]</tt>.
-
#
-
# This is due to the way Object#blank? handles boolean values:
-
# <tt>false.blank? # => true</tt>.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "can't be blank").
-
#
-
# There is also a list of default options supported by every validator:
-
# +:if+, +:unless+, +:on+ and +:strict+.
-
# See <tt>ActiveModel::Validation#validates</tt> for more information
-
1
def validates_presence_of(*attr_names)
-
validates_with PresenceValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/slice'
-
-
1
module ActiveModel
-
1
module Validations
-
1
module ClassMethods
-
# This method is a shortcut to all default validators and any custom
-
# validator classes ending in 'Validator'. Note that Rails default
-
# validators can be overridden inside specific classes by creating
-
# custom validator classes in their place such as PresenceValidator.
-
#
-
# Examples of using the default rails validators:
-
#
-
# validates :terms, acceptance: true
-
# validates :password, confirmation: true
-
# validates :username, exclusion: { in: %w(admin superuser) }
-
# validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, on: :create }
-
# validates :age, inclusion: { in: 0..9 }
-
# validates :first_name, length: { maximum: 30 }
-
# validates :age, numericality: true
-
# validates :username, presence: true
-
# validates :username, uniqueness: true
-
#
-
# The power of the +validates+ method comes when using custom validators
-
# and default validators in one call for a given attribute.
-
#
-
# class EmailValidator < ActiveModel::EachValidator
-
# def validate_each(record, attribute, value)
-
# record.errors.add attribute, (options[:message] || "is not an email") unless
-
# value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
-
# end
-
# end
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# attr_accessor :name, :email
-
#
-
# validates :name, presence: true, uniqueness: true, length: { maximum: 100 }
-
# validates :email, presence: true, email: true
-
# end
-
#
-
# Validator classes may also exist within the class being validated
-
# allowing custom modules of validators to be included as needed.
-
#
-
# class Film
-
# include ActiveModel::Validations
-
#
-
# class TitleValidator < ActiveModel::EachValidator
-
# def validate_each(record, attribute, value)
-
# record.errors.add attribute, "must start with 'the'" unless value =~ /\Athe/i
-
# end
-
# end
-
#
-
# validates :name, title: true
-
# end
-
#
-
# Additionally validator classes may be in another namespace and still
-
# used within any class.
-
#
-
# validates :name, :'film/title' => true
-
#
-
# The validators hash can also handle regular expressions, ranges, arrays
-
# and strings in shortcut form.
-
#
-
# validates :email, format: /@/
-
# validates :gender, inclusion: %w(male female)
-
# validates :password, length: 6..20
-
#
-
# When using shortcut form, ranges and arrays are passed to your
-
# validator's initializer as <tt>options[:in]</tt> while other types
-
# including regular expressions and strings are passed as <tt>options[:with]</tt>.
-
#
-
# There is also a list of options that could be used along with validators:
-
#
-
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
-
# validation contexts by default (+nil+), other options are <tt>:create</tt>
-
# and <tt>:update</tt>.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or
-
# +false+ value.
-
# * <tt>:strict</tt> - if the <tt>:strict</tt> option is set to true
-
# will raise ActiveModel::StrictValidationFailed instead of adding the error.
-
# <tt>:strict</tt> option can also be set to any other exception.
-
#
-
# Example:
-
#
-
# validates :password, presence: true, confirmation: true, if: :password_required?
-
# validates :token, uniqueness: true, strict: TokenGenerationException
-
#
-
#
-
# Finally, the options +:if+, +:unless+, +:on+, +:allow_blank+, +:allow_nil+, +:strict+
-
# and +:message+ can be given to one specific validator, as a hash:
-
#
-
# validates :password, presence: { if: :password_required?, message: 'is forgotten.' }, confirmation: true
-
1
def validates(*attributes)
-
defaults = attributes.extract_options!.dup
-
validations = defaults.slice!(*_validates_default_keys)
-
-
raise ArgumentError, "You need to supply at least one attribute" if attributes.empty?
-
raise ArgumentError, "You need to supply at least one validation" if validations.empty?
-
-
defaults[:attributes] = attributes
-
-
validations.each do |key, options|
-
next unless options
-
key = "#{key.to_s.camelize}Validator"
-
-
begin
-
validator = key.include?('::') ? key.constantize : const_get(key)
-
rescue NameError
-
raise ArgumentError, "Unknown validator: '#{key}'"
-
end
-
-
validates_with(validator, defaults.merge(_parse_validates_options(options)))
-
end
-
end
-
-
# This method is used to define validations that cannot be corrected by end
-
# users and are considered exceptional. So each validator defined with bang
-
# or <tt>:strict</tt> option set to <tt>true</tt> will always raise
-
# <tt>ActiveModel::StrictValidationFailed</tt> instead of adding error
-
# when validation fails. See <tt>validates</tt> for more information about
-
# the validation itself.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# attr_accessor :name
-
# validates! :name, presence: true
-
# end
-
#
-
# person = Person.new
-
# person.name = ''
-
# person.valid?
-
# # => ActiveModel::StrictValidationFailed: Name can't be blank
-
1
def validates!(*attributes)
-
options = attributes.extract_options!
-
options[:strict] = true
-
validates(*(attributes << options))
-
end
-
-
1
protected
-
-
# When creating custom validators, it might be useful to be able to specify
-
# additional default keys. This can be done by overwriting this method.
-
1
def _validates_default_keys # :nodoc:
-
[:if, :unless, :on, :allow_blank, :allow_nil , :strict]
-
end
-
-
1
def _parse_validates_options(options) # :nodoc:
-
case options
-
when TrueClass
-
{}
-
when Hash
-
options
-
when Range, Array
-
{ :in => options }
-
else
-
{ :with => options }
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveModel
-
1
module Validations
-
1
module HelperMethods
-
1
private
-
1
def _merge_attributes(attr_names)
-
options = attr_names.extract_options!.symbolize_keys
-
attr_names.flatten!
-
options[:attributes] = attr_names
-
options
-
end
-
end
-
-
1
class WithValidator < EachValidator # :nodoc:
-
1
def validate_each(record, attr, val)
-
method_name = options[:with]
-
-
if record.method(method_name).arity == 0
-
record.send method_name
-
else
-
record.send method_name, attr
-
end
-
end
-
end
-
-
1
module ClassMethods
-
# Passes the record off to the class or classes specified and allows them
-
# to add errors based on more complex conditions.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# if some_complex_logic
-
# record.errors.add :base, 'This record is invalid'
-
# end
-
# end
-
#
-
# private
-
# def some_complex_logic
-
# # ...
-
# end
-
# end
-
#
-
# You may also pass it multiple classes, like so:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator, MyOtherValidator, on: :create
-
# end
-
#
-
# Configuration options:
-
# * <tt>:on</tt> - Specifies when this validation is active
-
# (<tt>:create</tt> or <tt>:update</tt>.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>).
-
# The method, proc or string should return or evaluate to a +true+ or
-
# +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should not occur
-
# (e.g. <tt>unless: :skip_validation</tt>, or
-
# <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>).
-
# The method, proc or string should return or evaluate to a +true+ or
-
# +false+ value.
-
# * <tt>:strict</tt> - Specifies whether validation should be strict.
-
# See <tt>ActiveModel::Validation#validates!</tt> for more information.
-
#
-
# If you pass any additional configuration options, they will be passed
-
# to the class and available as +options+:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator, my_custom_key: 'my custom value'
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# options[:my_custom_key] # => "my custom value"
-
# end
-
# end
-
1
def validates_with(*args, &block)
-
options = args.extract_options!
-
args.each do |klass|
-
validator = klass.new(options, &block)
-
validator.setup(self) if validator.respond_to?(:setup)
-
-
if validator.respond_to?(:attributes) && !validator.attributes.empty?
-
validator.attributes.each do |attribute|
-
_validators[attribute.to_sym] << validator
-
end
-
else
-
_validators[nil] << validator
-
end
-
-
validate(validator, options)
-
end
-
end
-
end
-
-
# Passes the record off to the class or classes specified and allows them
-
# to add errors based on more complex conditions.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# validate :instance_validations
-
#
-
# def instance_validations
-
# validates_with MyValidator
-
# end
-
# end
-
#
-
# Please consult the class method documentation for more information on
-
# creating your own validator.
-
#
-
# You may also pass it multiple classes, like so:
-
#
-
# class Person
-
# include ActiveModel::Validations
-
#
-
# validate :instance_validations, on: :create
-
#
-
# def instance_validations
-
# validates_with MyValidator, MyOtherValidator
-
# end
-
# end
-
#
-
# Standard configuration options (<tt>:on</tt>, <tt>:if</tt> and
-
# <tt>:unless</tt>), which are available on the class version of
-
# +validates_with+, should instead be placed on the +validates+ method
-
# as these are applied and tested in the callback.
-
#
-
# If you pass any additional configuration options, they will be passed
-
# to the class and available as +options+, please refer to the
-
# class version of this method for more information.
-
1
def validates_with(*args, &block)
-
options = args.extract_options!
-
args.each do |klass|
-
validator = klass.new(options, &block)
-
validator.validate(self)
-
end
-
end
-
end
-
end
-
1
require "active_support/core_ext/module/anonymous"
-
-
1
module ActiveModel
-
-
# == Active \Model \Validator
-
#
-
# A simple base class that can be used along with
-
# ActiveModel::Validations::ClassMethods.validates_with
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# if some_complex_logic
-
# record.errors[:base] = "This record is invalid"
-
# end
-
# end
-
#
-
# private
-
# def some_complex_logic
-
# # ...
-
# end
-
# end
-
#
-
# Any class that inherits from ActiveModel::Validator must implement a method
-
# called +validate+ which accepts a +record+.
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# validates_with MyValidator
-
# end
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# record # => The person instance being validated
-
# options # => Any non-standard options passed to validates_with
-
# end
-
# end
-
#
-
# To cause a validation error, you must add to the +record+'s errors directly
-
# from within the validators message.
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def validate(record)
-
# record.errors.add :base, "This is some custom error message"
-
# record.errors.add :first_name, "This is some complex validation"
-
# # etc...
-
# end
-
# end
-
#
-
# To add behavior to the initialize method, use the following signature:
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def initialize(options)
-
# super
-
# @my_custom_field = options[:field_name] || :first_name
-
# end
-
# end
-
#
-
# The easiest way to add custom validators for validating individual attributes
-
# is with the convenient <tt>ActiveModel::EachValidator</tt>.
-
#
-
# class TitleValidator < ActiveModel::EachValidator
-
# def validate_each(record, attribute, value)
-
# record.errors.add attribute, 'must be Mr., Mrs., or Dr.' unless %w(Mr. Mrs. Dr.).include?(value)
-
# end
-
# end
-
#
-
# This can now be used in combination with the +validates+ method
-
# (see <tt>ActiveModel::Validations::ClassMethods.validates</tt> for more on this).
-
#
-
# class Person
-
# include ActiveModel::Validations
-
# attr_accessor :title
-
#
-
# validates :title, presence: true
-
# end
-
#
-
# Validator may also define a +setup+ instance method which will get called
-
# with the class that using that validator as its argument. This can be
-
# useful when there are prerequisites such as an +attr_accessor+ being present.
-
#
-
# class MyValidator < ActiveModel::Validator
-
# def setup(klass)
-
# klass.send :attr_accessor, :custom_attribute
-
# end
-
# end
-
#
-
# This setup method is only called when used with validation macros or the
-
# class level <tt>validates_with</tt> method.
-
1
class Validator
-
1
attr_reader :options
-
-
# Returns the kind of the validator.
-
#
-
# PresenceValidator.kind # => :presence
-
# UniquenessValidator.kind # => :uniqueness
-
1
def self.kind
-
@kind ||= name.split('::').last.underscore.sub(/_validator$/, '').to_sym unless anonymous?
-
end
-
-
# Accepts options that will be made available through the +options+ reader.
-
1
def initialize(options)
-
@options = options.freeze
-
end
-
-
# Return the kind for this validator.
-
#
-
# PresenceValidator.new.kind # => :presence
-
# UniquenessValidator.new.kind # => :uniqueness
-
1
def kind
-
self.class.kind
-
end
-
-
# Override this method in subclasses with validation logic, adding errors
-
# to the records +errors+ array where necessary.
-
1
def validate(record)
-
raise NotImplementedError, "Subclasses must implement a validate(record) method."
-
end
-
end
-
-
# +EachValidator+ is a validator which iterates through the attributes given
-
# in the options hash invoking the <tt>validate_each</tt> method passing in the
-
# record, attribute and value.
-
#
-
# All Active Model validations are built on top of this validator.
-
1
class EachValidator < Validator #:nodoc:
-
1
attr_reader :attributes
-
-
# Returns a new validator instance. All options will be available via the
-
# +options+ reader, however the <tt>:attributes</tt> option will be removed
-
# and instead be made available through the +attributes+ reader.
-
1
def initialize(options)
-
@attributes = Array(options.delete(:attributes))
-
raise ArgumentError, ":attributes cannot be blank" if @attributes.empty?
-
super
-
check_validity!
-
end
-
-
# Performs validation on the supplied record. By default this will call
-
# +validates_each+ to determine validity therefore subclasses should
-
# override +validates_each+ with validation logic.
-
1
def validate(record)
-
attributes.each do |attribute|
-
value = record.read_attribute_for_validation(attribute)
-
next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
-
validate_each(record, attribute, value)
-
end
-
end
-
-
# Override this method in subclasses with the validation logic, adding
-
# errors to the records +errors+ array where necessary.
-
1
def validate_each(record, attribute, value)
-
raise NotImplementedError, "Subclasses must implement a validate_each(record, attribute, value) method"
-
end
-
-
# Hook method that gets called by the initializer allowing verification
-
# that the arguments supplied are valid. You could for example raise an
-
# +ArgumentError+ when invalid options are supplied.
-
1
def check_validity!
-
end
-
end
-
-
# +BlockValidator+ is a special +EachValidator+ which receives a block on initialization
-
# and call this block for each attribute being validated. +validates_each+ uses this validator.
-
1
class BlockValidator < EachValidator #:nodoc:
-
1
def initialize(options, &block)
-
@block = block
-
super
-
end
-
-
1
private
-
-
1
def validate_each(record, attribute, value)
-
@block.call(record, attribute, value)
-
end
-
end
-
end
-
1
module ActiveModel
-
1
module VERSION #:nodoc:
-
1
MAJOR = 4
-
1
MINOR = 0
-
1
TINY = 0
-
1
PRE = "beta"
-
-
1
STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
-
end
-
end
-
#--
-
# Copyright (c) 2004-2012 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
1
require 'simplecov'
-
1
SimpleCov.start
-
1
puts "Started SimpleCov active_record.rb"
-
1
require 'active_support'
-
1
require 'active_support/rails'
-
1
require 'active_model'
-
1
require 'arel'
-
1
require 'active_record/deprecated_finders'
-
-
1
require 'active_record/version'
-
-
1
module ActiveRecord
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Base
-
1
autoload :Callbacks
-
1
autoload :Core
-
1
autoload :CounterCache
-
1
autoload :ConnectionHandling
-
1
autoload :DynamicMatchers
-
1
autoload :Explain
-
1
autoload :Inheritance
-
1
autoload :Integration
-
1
autoload :Migration
-
1
autoload :Migrator, 'active_record/migration'
-
1
autoload :ModelSchema
-
1
autoload :NestedAttributes
-
1
autoload :Observer
-
1
autoload :Persistence
-
1
autoload :QueryCache
-
1
autoload :Querying
-
1
autoload :ReadonlyAttributes
-
1
autoload :Reflection
-
1
autoload :Sanitization
-
1
autoload :Schema
-
1
autoload :SchemaDumper
-
1
autoload :SchemaMigration
-
1
autoload :Scoping
-
1
autoload :Serialization
-
1
autoload :Store
-
1
autoload :Timestamp
-
1
autoload :Transactions
-
1
autoload :Translation
-
1
autoload :Validations
-
-
1
eager_autoload do
-
1
autoload :ActiveRecordError, 'active_record/errors'
-
1
autoload :ConnectionNotEstablished, 'active_record/errors'
-
1
autoload :ConnectionAdapters, 'active_record/connection_adapters/abstract_adapter'
-
-
1
autoload :Aggregations
-
1
autoload :Associations
-
1
autoload :AttributeMethods
-
1
autoload :AttributeAssignment
-
1
autoload :AutosaveAssociation
-
-
1
autoload :Relation
-
1
autoload :NullRelation
-
-
1
autoload_under 'relation' do
-
1
autoload :QueryMethods
-
1
autoload :FinderMethods
-
1
autoload :Calculations
-
1
autoload :PredicateBuilder
-
1
autoload :SpawnMethods
-
1
autoload :Batches
-
1
autoload :Delegation
-
end
-
-
1
autoload :Result
-
end
-
-
1
module Coders
-
1
autoload :YAMLColumn, 'active_record/coders/yaml_column'
-
end
-
-
1
module AttributeMethods
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :BeforeTypeCast
-
1
autoload :Dirty
-
1
autoload :PrimaryKey
-
1
autoload :Query
-
1
autoload :Read
-
1
autoload :TimeZoneConversion
-
1
autoload :Write
-
1
autoload :Serialization
-
end
-
end
-
-
1
module Locking
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :Optimistic
-
1
autoload :Pessimistic
-
end
-
end
-
-
1
module ConnectionAdapters
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :AbstractAdapter
-
1
autoload :ConnectionManagement, "active_record/connection_adapters/abstract/connection_pool"
-
end
-
end
-
-
1
module Scoping
-
1
extend ActiveSupport::Autoload
-
-
1
eager_autoload do
-
1
autoload :Named
-
1
autoload :Default
-
end
-
end
-
-
1
module Tasks
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :DatabaseTasks
-
1
autoload :SQLiteDatabaseTasks, 'active_record/tasks/sqlite_database_tasks'
-
1
autoload :MySQLDatabaseTasks, 'active_record/tasks/mysql_database_tasks'
-
1
autoload :PostgreSQLDatabaseTasks,
-
'active_record/tasks/postgresql_database_tasks'
-
end
-
-
1
autoload :TestCase
-
1
autoload :TestFixtures, 'active_record/fixtures'
-
-
1
def self.eager_load!
-
super
-
ActiveRecord::Locking.eager_load!
-
ActiveRecord::Scoping.eager_load!
-
ActiveRecord::Associations.eager_load!
-
ActiveRecord::AttributeMethods.eager_load!
-
ActiveRecord::ConnectionAdapters.eager_load!
-
end
-
end
-
-
1
ActiveSupport.on_load(:active_record) do
-
1
Arel::Table.engine = self
-
end
-
-
1
ActiveSupport.on_load(:i18n) do
-
1
I18n.load_path << File.dirname(__FILE__) + '/active_record/locale/en.yml'
-
end
-
1
module ActiveRecord
-
# = Active Record Aggregations
-
1
module Aggregations # :nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
def clear_aggregation_cache #:nodoc:
-
@aggregation_cache.clear if persisted?
-
end
-
-
# Active Record implements aggregation through a macro-like class method called +composed_of+
-
# for representing attributes as value objects. It expresses relationships like "Account [is]
-
# composed of Money [among other things]" or "Person [is] composed of [an] address". Each call
-
# to the macro adds a description of how the value objects are created from the attributes of
-
# the entity object (when the entity is initialized either as a new object or from finding an
-
# existing object) and how it can be turned back into attributes (when the entity is saved to
-
# the database).
-
#
-
# class Customer < ActiveRecord::Base
-
# composed_of :balance, :class_name => "Money", :mapping => %w(balance amount)
-
# composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ]
-
# end
-
#
-
# The customer class now has the following methods to manipulate the value objects:
-
# * <tt>Customer#balance, Customer#balance=(money)</tt>
-
# * <tt>Customer#address, Customer#address=(address)</tt>
-
#
-
# These methods will operate with value objects like the ones described below:
-
#
-
# class Money
-
# include Comparable
-
# attr_reader :amount, :currency
-
# EXCHANGE_RATES = { "USD_TO_DKK" => 6 }
-
#
-
# def initialize(amount, currency = "USD")
-
# @amount, @currency = amount, currency
-
# end
-
#
-
# def exchange_to(other_currency)
-
# exchanged_amount = (amount * EXCHANGE_RATES["#{currency}_TO_#{other_currency}"]).floor
-
# Money.new(exchanged_amount, other_currency)
-
# end
-
#
-
# def ==(other_money)
-
# amount == other_money.amount && currency == other_money.currency
-
# end
-
#
-
# def <=>(other_money)
-
# if currency == other_money.currency
-
# amount <=> other_money.amount
-
# else
-
# amount <=> other_money.exchange_to(currency).amount
-
# end
-
# end
-
# end
-
#
-
# class Address
-
# attr_reader :street, :city
-
# def initialize(street, city)
-
# @street, @city = street, city
-
# end
-
#
-
# def close_to?(other_address)
-
# city == other_address.city
-
# end
-
#
-
# def ==(other_address)
-
# city == other_address.city && street == other_address.street
-
# end
-
# end
-
#
-
# Now it's possible to access attributes from the database through the value objects instead. If
-
# you choose to name the composition the same as the attribute's name, it will be the only way to
-
# access that attribute. That's the case with our +balance+ attribute. You interact with the value
-
# objects just like you would with any other attribute:
-
#
-
# customer.balance = Money.new(20) # sets the Money value object and the attribute
-
# customer.balance # => Money value object
-
# customer.balance.exchange_to("DKK") # => Money.new(120, "DKK")
-
# customer.balance > Money.new(10) # => true
-
# customer.balance == Money.new(20) # => true
-
# customer.balance < Money.new(5) # => false
-
#
-
# Value objects can also be composed of multiple attributes, such as the case of Address. The order
-
# of the mappings will determine the order of the parameters.
-
#
-
# customer.address_street = "Hyancintvej"
-
# customer.address_city = "Copenhagen"
-
# customer.address # => Address.new("Hyancintvej", "Copenhagen")
-
#
-
# customer.address_street = "Vesterbrogade"
-
# customer.address # => Address.new("Hyancintvej", "Copenhagen")
-
# customer.clear_aggregation_cache
-
# customer.address # => Address.new("Vesterbrogade", "Copenhagen")
-
#
-
# customer.address = Address.new("May Street", "Chicago")
-
# customer.address_street # => "May Street"
-
# customer.address_city # => "Chicago"
-
#
-
# == Writing value objects
-
#
-
# Value objects are immutable and interchangeable objects that represent a given value, such as
-
# a Money object representing $5. Two Money objects both representing $5 should be equal (through
-
# methods such as <tt>==</tt> and <tt><=></tt> from Comparable if ranking makes sense). This is
-
# unlike entity objects where equality is determined by identity. An entity class such as Customer can
-
# easily have two different objects that both have an address on Hyancintvej. Entity identity is
-
# determined by object or relational unique identifiers (such as primary keys). Normal
-
# ActiveRecord::Base classes are entity objects.
-
#
-
# It's also important to treat the value objects as immutable. Don't allow the Money object to have
-
# its amount changed after creation. Create a new Money object with the new value instead. The
-
# Money#exchange_to method is an example of this. It returns a new value object instead of changing
-
# its own values. Active Record won't persist value objects that have been changed through means
-
# other than the writer method.
-
#
-
# The immutable requirement is enforced by Active Record by freezing any object assigned as a value
-
# object. Attempting to change it afterwards will result in a ActiveSupport::FrozenObjectError.
-
#
-
# Read more about value objects on http://c2.com/cgi/wiki?ValueObject and on the dangers of not
-
# keeping value objects immutable on http://c2.com/cgi/wiki?ValueObjectsShouldBeImmutable
-
#
-
# == Custom constructors and converters
-
#
-
# By default value objects are initialized by calling the <tt>new</tt> constructor of the value
-
# class passing each of the mapped attributes, in the order specified by the <tt>:mapping</tt>
-
# option, as arguments. If the value class doesn't support this convention then +composed_of+ allows
-
# a custom constructor to be specified.
-
#
-
# When a new value is assigned to the value object, the default assumption is that the new value
-
# is an instance of the value class. Specifying a custom converter allows the new value to be automatically
-
# converted to an instance of value class if necessary.
-
#
-
# For example, the NetworkResource model has +network_address+ and +cidr_range+ attributes that
-
# should be aggregated using the NetAddr::CIDR value class (http://netaddr.rubyforge.org). The constructor
-
# for the value class is called +create+ and it expects a CIDR address string as a parameter. New
-
# values can be assigned to the value object using either another NetAddr::CIDR object, a string
-
# or an array. The <tt>:constructor</tt> and <tt>:converter</tt> options can be used to meet
-
# these requirements:
-
#
-
# class NetworkResource < ActiveRecord::Base
-
# composed_of :cidr,
-
# :class_name => 'NetAddr::CIDR',
-
# :mapping => [ %w(network_address network), %w(cidr_range bits) ],
-
# :allow_nil => true,
-
# :constructor => Proc.new { |network_address, cidr_range| NetAddr::CIDR.create("#{network_address}/#{cidr_range}") },
-
# :converter => Proc.new { |value| NetAddr::CIDR.create(value.is_a?(Array) ? value.join('/') : value) }
-
# end
-
#
-
# # This calls the :constructor
-
# network_resource = NetworkResource.new(:network_address => '192.168.0.1', :cidr_range => 24)
-
#
-
# # These assignments will both use the :converter
-
# network_resource.cidr = [ '192.168.2.1', 8 ]
-
# network_resource.cidr = '192.168.0.1/24'
-
#
-
# # This assignment won't use the :converter as the value is already an instance of the value class
-
# network_resource.cidr = NetAddr::CIDR.create('192.168.2.1/8')
-
#
-
# # Saving and then reloading will use the :constructor on reload
-
# network_resource.save
-
# network_resource.reload
-
#
-
# == Finding records by a value object
-
#
-
# Once a +composed_of+ relationship is specified for a model, records can be loaded from the database
-
# by specifying an instance of the value object in the conditions hash. The following example
-
# finds all customers with +balance_amount+ equal to 20 and +balance_currency+ equal to "USD":
-
#
-
# Customer.where(:balance => Money.new(20, "USD")).all
-
#
-
1
module ClassMethods
-
# Adds reader and writer methods for manipulating a value object:
-
# <tt>composed_of :address</tt> adds <tt>address</tt> and <tt>address=(new_address)</tt> methods.
-
#
-
# Options are:
-
# * <tt>:class_name</tt> - Specifies the class name of the association. Use it only if that name
-
# can't be inferred from the part id. So <tt>composed_of :address</tt> will by default be linked
-
# to the Address class, but if the real class name is CompanyAddress, you'll have to specify it
-
# with this option.
-
# * <tt>:mapping</tt> - Specifies the mapping of entity attributes to attributes of the value
-
# object. Each mapping is represented as an array where the first item is the name of the
-
# entity attribute and the second item is the name of the attribute in the value object. The
-
# order in which mappings are defined determines the order in which attributes are sent to the
-
# value class constructor.
-
# * <tt>:allow_nil</tt> - Specifies that the value object will not be instantiated when all mapped
-
# attributes are +nil+. Setting the value object to +nil+ has the effect of writing +nil+ to all
-
# mapped attributes.
-
# This defaults to +false+.
-
# * <tt>:constructor</tt> - A symbol specifying the name of the constructor method or a Proc that
-
# is called to initialize the value object. The constructor is passed all of the mapped attributes,
-
# in the order that they are defined in the <tt>:mapping option</tt>, as arguments and uses them
-
# to instantiate a <tt>:class_name</tt> object.
-
# The default is <tt>:new</tt>.
-
# * <tt>:converter</tt> - A symbol specifying the name of a class method of <tt>:class_name</tt>
-
# or a Proc that is called when a new value is assigned to the value object. The converter is
-
# passed the single value that is used in the assignment and is only called if the new value is
-
# not an instance of <tt>:class_name</tt>. If <tt>:allow_nil</tt> is set to true, the converter
-
# can return nil to skip the assignment.
-
#
-
# Option examples:
-
# composed_of :temperature, :mapping => %w(reading celsius)
-
# composed_of :balance, :class_name => "Money", :mapping => %w(balance amount),
-
# :converter => Proc.new { |balance| balance.to_money }
-
# composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ]
-
# composed_of :gps_location
-
# composed_of :gps_location, :allow_nil => true
-
# composed_of :ip_address,
-
# :class_name => 'IPAddr',
-
# :mapping => %w(ip to_i),
-
# :constructor => Proc.new { |ip| IPAddr.new(ip, Socket::AF_INET) },
-
# :converter => Proc.new { |ip| ip.is_a?(Integer) ? IPAddr.new(ip, Socket::AF_INET) : IPAddr.new(ip.to_s) }
-
#
-
1
def composed_of(part_id, options = {})
-
options.assert_valid_keys(:class_name, :mapping, :allow_nil, :constructor, :converter)
-
-
name = part_id.id2name
-
class_name = options[:class_name] || name.camelize
-
mapping = options[:mapping] || [ name, name ]
-
mapping = [ mapping ] unless mapping.first.is_a?(Array)
-
allow_nil = options[:allow_nil] || false
-
constructor = options[:constructor] || :new
-
converter = options[:converter]
-
-
reader_method(name, class_name, mapping, allow_nil, constructor)
-
writer_method(name, class_name, mapping, allow_nil, converter)
-
-
create_reflection(:composed_of, part_id, nil, options, self)
-
end
-
-
1
private
-
1
def reader_method(name, class_name, mapping, allow_nil, constructor)
-
define_method(name) do
-
if @aggregation_cache[name].nil? && (!allow_nil || mapping.any? {|pair| !read_attribute(pair.first).nil? })
-
attrs = mapping.collect {|pair| read_attribute(pair.first)}
-
object = constructor.respond_to?(:call) ?
-
constructor.call(*attrs) :
-
class_name.constantize.send(constructor, *attrs)
-
@aggregation_cache[name] = object
-
end
-
@aggregation_cache[name]
-
end
-
end
-
-
1
def writer_method(name, class_name, mapping, allow_nil, converter)
-
define_method("#{name}=") do |part|
-
klass = class_name.constantize
-
unless part.is_a?(klass) || converter.nil? || part.nil?
-
part = converter.respond_to?(:call) ? converter.call(part) : klass.send(converter, part)
-
end
-
-
if part.nil? && allow_nil
-
mapping.each { |pair| self[pair.first] = nil }
-
@aggregation_cache[name] = nil
-
else
-
mapping.each { |pair| self[pair.first] = part.send(pair.last) }
-
@aggregation_cache[name] = part.freeze
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/enumerable'
-
1
require 'active_support/core_ext/string/conversions'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'active_support/dependencies/autoload'
-
1
require 'active_support/concern'
-
1
require 'active_record/errors'
-
-
1
module ActiveRecord
-
1
class InverseOfAssociationNotFoundError < ActiveRecordError #:nodoc:
-
1
def initialize(reflection, associated_class = nil)
-
super("Could not find the inverse association for #{reflection.name} (#{reflection.options[:inverse_of].inspect} in #{associated_class.nil? ? reflection.class_name : associated_class.name})")
-
end
-
end
-
-
1
class HasManyThroughAssociationNotFoundError < ActiveRecordError #:nodoc:
-
1
def initialize(owner_class_name, reflection)
-
super("Could not find the association #{reflection.options[:through].inspect} in model #{owner_class_name}")
-
end
-
end
-
-
1
class HasManyThroughAssociationPolymorphicSourceError < ActiveRecordError #:nodoc:
-
1
def initialize(owner_class_name, reflection, source_reflection)
-
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' on the polymorphic object '#{source_reflection.class_name}##{source_reflection.name}' without 'source_type'. Try adding 'source_type: \"#{reflection.name.to_s.classify}\"' to 'has_many :through' definition.")
-
end
-
end
-
-
1
class HasManyThroughAssociationPolymorphicThroughError < ActiveRecordError #:nodoc:
-
1
def initialize(owner_class_name, reflection)
-
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' which goes through the polymorphic association '#{owner_class_name}##{reflection.through_reflection.name}'.")
-
end
-
end
-
-
1
class HasManyThroughAssociationPointlessSourceTypeError < ActiveRecordError #:nodoc:
-
1
def initialize(owner_class_name, reflection, source_reflection)
-
super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' with a :source_type option if the '#{reflection.through_reflection.class_name}##{source_reflection.name}' is not polymorphic. Try removing :source_type on your association.")
-
end
-
end
-
-
1
class HasOneThroughCantAssociateThroughCollection < ActiveRecordError #:nodoc:
-
1
def initialize(owner_class_name, reflection, through_reflection)
-
super("Cannot have a has_one :through association '#{owner_class_name}##{reflection.name}' where the :through association '#{owner_class_name}##{through_reflection.name}' is a collection. Specify a has_one or belongs_to association in the :through option instead.")
-
end
-
end
-
-
1
class HasManyThroughSourceAssociationNotFoundError < ActiveRecordError #:nodoc:
-
1
def initialize(reflection)
-
through_reflection = reflection.through_reflection
-
source_reflection_names = reflection.source_reflection_names
-
source_associations = reflection.through_reflection.klass.reflect_on_all_associations.collect { |a| a.name.inspect }
-
super("Could not find the source association(s) #{source_reflection_names.collect{ |a| a.inspect }.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => <name>'. Is it one of #{source_associations.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)}?")
-
end
-
end
-
-
1
class HasManyThroughCantAssociateThroughHasOneOrManyReflection < ActiveRecordError #:nodoc:
-
1
def initialize(owner, reflection)
-
super("Cannot modify association '#{owner.class.name}##{reflection.name}' because the source reflection class '#{reflection.source_reflection.class_name}' is associated to '#{reflection.through_reflection.class_name}' via :#{reflection.source_reflection.macro}.")
-
end
-
end
-
-
1
class HasManyThroughCantAssociateNewRecords < ActiveRecordError #:nodoc:
-
1
def initialize(owner, reflection)
-
super("Cannot associate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to create the has_many :through record associating them.")
-
end
-
end
-
-
1
class HasManyThroughCantDissociateNewRecords < ActiveRecordError #:nodoc:
-
1
def initialize(owner, reflection)
-
super("Cannot dissociate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to delete the has_many :through record associating them.")
-
end
-
end
-
-
1
class HasManyThroughNestedAssociationsAreReadonly < ActiveRecordError #:nodoc:
-
1
def initialize(owner, reflection)
-
super("Cannot modify association '#{owner.class.name}##{reflection.name}' because it goes through more than one other association.")
-
end
-
end
-
-
1
class HasAndBelongsToManyAssociationForeignKeyNeeded < ActiveRecordError #:nodoc:
-
1
def initialize(reflection)
-
super("Cannot create self referential has_and_belongs_to_many association on '#{reflection.class_name rescue nil}##{reflection.name rescue nil}'. :association_foreign_key cannot be the same as the :foreign_key.")
-
end
-
end
-
-
1
class EagerLoadPolymorphicError < ActiveRecordError #:nodoc:
-
1
def initialize(reflection)
-
super("Can not eagerly load the polymorphic association #{reflection.name.inspect}")
-
end
-
end
-
-
1
class ReadOnlyAssociation < ActiveRecordError #:nodoc:
-
1
def initialize(reflection)
-
super("Can not add to a has_many :through association. Try adding to #{reflection.through_reflection.name.inspect}.")
-
end
-
end
-
-
# This error is raised when trying to destroy a parent instance in N:1 or 1:1 associations
-
# (has_many, has_one) when there is at least 1 child associated instance.
-
# ex: if @project.tasks.size > 0, DeleteRestrictionError will be raised when trying to destroy @project
-
1
class DeleteRestrictionError < ActiveRecordError #:nodoc:
-
1
def initialize(name)
-
super("Cannot delete record because of dependent #{name}")
-
end
-
end
-
-
# See ActiveRecord::Associations::ClassMethods for documentation.
-
1
module Associations # :nodoc:
-
1
extend ActiveSupport::Autoload
-
1
extend ActiveSupport::Concern
-
-
# These classes will be loaded when associations are created.
-
# So there is no need to eager load them.
-
1
autoload :Association, 'active_record/associations/association'
-
1
autoload :SingularAssociation, 'active_record/associations/singular_association'
-
1
autoload :CollectionAssociation, 'active_record/associations/collection_association'
-
1
autoload :CollectionProxy, 'active_record/associations/collection_proxy'
-
-
1
autoload :BelongsToAssociation, 'active_record/associations/belongs_to_association'
-
1
autoload :BelongsToPolymorphicAssociation, 'active_record/associations/belongs_to_polymorphic_association'
-
1
autoload :HasAndBelongsToManyAssociation, 'active_record/associations/has_and_belongs_to_many_association'
-
1
autoload :HasManyAssociation, 'active_record/associations/has_many_association'
-
1
autoload :HasManyThroughAssociation, 'active_record/associations/has_many_through_association'
-
1
autoload :HasOneAssociation, 'active_record/associations/has_one_association'
-
1
autoload :HasOneThroughAssociation, 'active_record/associations/has_one_through_association'
-
1
autoload :ThroughAssociation, 'active_record/associations/through_association'
-
-
1
module Builder #:nodoc:
-
1
autoload :Association, 'active_record/associations/builder/association'
-
1
autoload :SingularAssociation, 'active_record/associations/builder/singular_association'
-
1
autoload :CollectionAssociation, 'active_record/associations/builder/collection_association'
-
-
1
autoload :BelongsTo, 'active_record/associations/builder/belongs_to'
-
1
autoload :HasOne, 'active_record/associations/builder/has_one'
-
1
autoload :HasMany, 'active_record/associations/builder/has_many'
-
1
autoload :HasAndBelongsToMany, 'active_record/associations/builder/has_and_belongs_to_many'
-
end
-
-
1
eager_autoload do
-
1
autoload :Preloader, 'active_record/associations/preloader'
-
1
autoload :JoinDependency, 'active_record/associations/join_dependency'
-
1
autoload :AssociationScope, 'active_record/associations/association_scope'
-
1
autoload :AliasTracker, 'active_record/associations/alias_tracker'
-
1
autoload :JoinHelper, 'active_record/associations/join_helper'
-
end
-
-
# Clears out the association cache.
-
1
def clear_association_cache #:nodoc:
-
@association_cache.clear if persisted?
-
end
-
-
# :nodoc:
-
1
attr_reader :association_cache
-
-
# Returns the association instance for the given name, instantiating it if it doesn't already exist
-
1
def association(name) #:nodoc:
-
association = association_instance_get(name)
-
-
if association.nil?
-
reflection = self.class.reflect_on_association(name)
-
association = reflection.association_class.new(self, reflection)
-
association_instance_set(name, association)
-
end
-
-
association
-
end
-
-
1
private
-
# Returns the specified association instance if it responds to :loaded?, nil otherwise.
-
1
def association_instance_get(name)
-
@association_cache[name.to_sym]
-
end
-
-
# Set the specified association instance.
-
1
def association_instance_set(name, association)
-
@association_cache[name] = association
-
end
-
-
# Associations are a set of macro-like class methods for tying objects together through
-
# foreign keys. They express relationships like "Project has one Project Manager"
-
# or "Project belongs to a Portfolio". Each macro adds a number of methods to the
-
# class which are specialized according to the collection or association symbol and the
-
# options hash. It works much the same way as Ruby's own <tt>attr*</tt>
-
# methods.
-
#
-
# class Project < ActiveRecord::Base
-
# belongs_to :portfolio
-
# has_one :project_manager
-
# has_many :milestones
-
# has_and_belongs_to_many :categories
-
# end
-
#
-
# The project class now has the following methods (and more) to ease the traversal and
-
# manipulation of its relationships:
-
# * <tt>Project#portfolio, Project#portfolio=(portfolio), Project#portfolio.nil?</tt>
-
# * <tt>Project#project_manager, Project#project_manager=(project_manager), Project#project_manager.nil?,</tt>
-
# * <tt>Project#milestones.empty?, Project#milestones.size, Project#milestones, Project#milestones<<(milestone),</tt>
-
# <tt>Project#milestones.delete(milestone), Project#milestones.destroy(mileston), Project#milestones.find(milestone_id),</tt>
-
# <tt>Project#milestones.all(options), Project#milestones.build, Project#milestones.create</tt>
-
# * <tt>Project#categories.empty?, Project#categories.size, Project#categories, Project#categories<<(category1),</tt>
-
# <tt>Project#categories.delete(category1), Project#categories.destroy(category1)</tt>
-
#
-
# === A word of warning
-
#
-
# Don't create associations that have the same name as instance methods of
-
# <tt>ActiveRecord::Base</tt>. Since the association adds a method with that name to
-
# its model, it will override the inherited method and break things.
-
# For instance, +attributes+ and +connection+ would be bad choices for association names.
-
#
-
# == Auto-generated methods
-
#
-
# === Singular associations (one-to-one)
-
# | | belongs_to |
-
# generated methods | belongs_to | :polymorphic | has_one
-
# ----------------------------------+------------+--------------+---------
-
# other | X | X | X
-
# other=(other) | X | X | X
-
# build_other(attributes={}) | X | | X
-
# create_other(attributes={}) | X | | X
-
# create_other!(attributes={}) | X | | X
-
#
-
# ===Collection associations (one-to-many / many-to-many)
-
# | | | has_many
-
# generated methods | habtm | has_many | :through
-
# ----------------------------------+-------+----------+----------
-
# others | X | X | X
-
# others=(other,other,...) | X | X | X
-
# other_ids | X | X | X
-
# other_ids=(id,id,...) | X | X | X
-
# others<< | X | X | X
-
# others.push | X | X | X
-
# others.concat | X | X | X
-
# others.build(attributes={}) | X | X | X
-
# others.create(attributes={}) | X | X | X
-
# others.create!(attributes={}) | X | X | X
-
# others.size | X | X | X
-
# others.length | X | X | X
-
# others.count | X | X | X
-
# others.sum(args*,&block) | X | X | X
-
# others.empty? | X | X | X
-
# others.clear | X | X | X
-
# others.delete(other,other,...) | X | X | X
-
# others.delete_all | X | X | X
-
# others.destroy(other,other,...) | X | X | X
-
# others.destroy_all | X | X | X
-
# others.find(*args) | X | X | X
-
# others.exists? | X | X | X
-
# others.uniq | X | X | X
-
# others.reset | X | X | X
-
#
-
# === Overriding generated methods
-
#
-
# Association methods are generated in a module that is included into the model class,
-
# which allows you to easily override with your own methods and call the original
-
# generated method with +super+. For example:
-
#
-
# class Car < ActiveRecord::Base
-
# belongs_to :owner
-
# belongs_to :old_owner
-
# def owner=(new_owner)
-
# self.old_owner = self.owner
-
# super
-
# end
-
# end
-
#
-
# If your model class is <tt>Project</tt>, the module is
-
# named <tt>Project::GeneratedFeatureMethods</tt>. The GeneratedFeatureMethods module is
-
# included in the model class immediately after the (anonymous) generated attributes methods
-
# module, meaning an association will override the methods for an attribute with the same name.
-
#
-
# == Cardinality and associations
-
#
-
# Active Record associations can be used to describe one-to-one, one-to-many and many-to-many
-
# relationships between models. Each model uses an association to describe its role in
-
# the relation. The +belongs_to+ association is always used in the model that has
-
# the foreign key.
-
#
-
# === One-to-one
-
#
-
# Use +has_one+ in the base, and +belongs_to+ in the associated model.
-
#
-
# class Employee < ActiveRecord::Base
-
# has_one :office
-
# end
-
# class Office < ActiveRecord::Base
-
# belongs_to :employee # foreign key - employee_id
-
# end
-
#
-
# === One-to-many
-
#
-
# Use +has_many+ in the base, and +belongs_to+ in the associated model.
-
#
-
# class Manager < ActiveRecord::Base
-
# has_many :employees
-
# end
-
# class Employee < ActiveRecord::Base
-
# belongs_to :manager # foreign key - manager_id
-
# end
-
#
-
# === Many-to-many
-
#
-
# There are two ways to build a many-to-many relationship.
-
#
-
# The first way uses a +has_many+ association with the <tt>:through</tt> option and a join model, so
-
# there are two stages of associations.
-
#
-
# class Assignment < ActiveRecord::Base
-
# belongs_to :programmer # foreign key - programmer_id
-
# belongs_to :project # foreign key - project_id
-
# end
-
# class Programmer < ActiveRecord::Base
-
# has_many :assignments
-
# has_many :projects, :through => :assignments
-
# end
-
# class Project < ActiveRecord::Base
-
# has_many :assignments
-
# has_many :programmers, :through => :assignments
-
# end
-
#
-
# For the second way, use +has_and_belongs_to_many+ in both models. This requires a join table
-
# that has no corresponding model or primary key.
-
#
-
# class Programmer < ActiveRecord::Base
-
# has_and_belongs_to_many :projects # foreign keys in the join table
-
# end
-
# class Project < ActiveRecord::Base
-
# has_and_belongs_to_many :programmers # foreign keys in the join table
-
# end
-
#
-
# Choosing which way to build a many-to-many relationship is not always simple.
-
# If you need to work with the relationship model as its own entity,
-
# use <tt>has_many :through</tt>. Use +has_and_belongs_to_many+ when working with legacy schemas or when
-
# you never work directly with the relationship itself.
-
#
-
# == Is it a +belongs_to+ or +has_one+ association?
-
#
-
# Both express a 1-1 relationship. The difference is mostly where to place the foreign
-
# key, which goes on the table for the class declaring the +belongs_to+ relationship.
-
#
-
# class User < ActiveRecord::Base
-
# # I reference an account.
-
# belongs_to :account
-
# end
-
#
-
# class Account < ActiveRecord::Base
-
# # One user references me.
-
# has_one :user
-
# end
-
#
-
# The tables for these classes could look something like:
-
#
-
# CREATE TABLE users (
-
# id int(11) NOT NULL auto_increment,
-
# account_id int(11) default NULL,
-
# name varchar default NULL,
-
# PRIMARY KEY (id)
-
# )
-
#
-
# CREATE TABLE accounts (
-
# id int(11) NOT NULL auto_increment,
-
# name varchar default NULL,
-
# PRIMARY KEY (id)
-
# )
-
#
-
# == Unsaved objects and associations
-
#
-
# You can manipulate objects and associations before they are saved to the database, but
-
# there is some special behavior you should be aware of, mostly involving the saving of
-
# associated objects.
-
#
-
# You can set the :autosave option on a <tt>has_one</tt>, <tt>belongs_to</tt>,
-
# <tt>has_many</tt>, or <tt>has_and_belongs_to_many</tt> association. Setting it
-
# to +true+ will _always_ save the members, whereas setting it to +false+ will
-
# _never_ save the members. More details about :autosave option is available at
-
# autosave_association.rb .
-
#
-
# === One-to-one associations
-
#
-
# * Assigning an object to a +has_one+ association automatically saves that object and
-
# the object being replaced (if there is one), in order to update their foreign
-
# keys - except if the parent object is unsaved (<tt>new_record? == true</tt>).
-
# * If either of these saves fail (due to one of the objects being invalid), an
-
# <tt>ActiveRecord::RecordNotSaved</tt> exception is raised and the assignment is
-
# cancelled.
-
# * If you wish to assign an object to a +has_one+ association without saving it,
-
# use the <tt>build_association</tt> method (documented below). The object being
-
# replaced will still be saved to update its foreign key.
-
# * Assigning an object to a +belongs_to+ association does not save the object, since
-
# the foreign key field belongs on the parent. It does not save the parent either.
-
#
-
# === Collections
-
#
-
# * Adding an object to a collection (+has_many+ or +has_and_belongs_to_many+) automatically
-
# saves that object, except if the parent object (the owner of the collection) is not yet
-
# stored in the database.
-
# * If saving any of the objects being added to a collection (via <tt>push</tt> or similar)
-
# fails, then <tt>push</tt> returns +false+.
-
# * If saving fails while replacing the collection (via <tt>association=</tt>), an
-
# <tt>ActiveRecord::RecordNotSaved</tt> exception is raised and the assignment is
-
# cancelled.
-
# * You can add an object to a collection without automatically saving it by using the
-
# <tt>collection.build</tt> method (documented below).
-
# * All unsaved (<tt>new_record? == true</tt>) members of the collection are automatically
-
# saved when the parent is saved.
-
#
-
# == Customizing the query
-
#
-
# Associations are built from <tt>Relation</tt>s, and you can use the <tt>Relation</tt> syntax
-
# to customize them. For example, to add a condition:
-
#
-
# class Blog < ActiveRecord::Base
-
# has_many :published_posts, -> { where published: true }, class_name: 'Post'
-
# end
-
#
-
# Inside the <tt>-> { ... }</tt> block you can use all of the usual <tt>Relation</tt> methods.
-
#
-
# === Accessing the owner object
-
#
-
# Sometimes it is useful to have access to the owner object when building the query. The owner
-
# is passed as a parameter to the block. For example, the following association would find all
-
# events that occur on the user's birthday:
-
#
-
# class User < ActiveRecord::Base
-
# has_many :birthday_events, ->(user) { where starts_on: user.birthday }, class_name: 'Event'
-
# end
-
#
-
# == Association callbacks
-
#
-
# Similar to the normal callbacks that hook into the life cycle of an Active Record object,
-
# you can also define callbacks that get triggered when you add an object to or remove an
-
# object from an association collection.
-
#
-
# class Project
-
# has_and_belongs_to_many :developers, :after_add => :evaluate_velocity
-
#
-
# def evaluate_velocity(developer)
-
# ...
-
# end
-
# end
-
#
-
# It's possible to stack callbacks by passing them as an array. Example:
-
#
-
# class Project
-
# has_and_belongs_to_many :developers,
-
# :after_add => [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}]
-
# end
-
#
-
# Possible callbacks are: +before_add+, +after_add+, +before_remove+ and +after_remove+.
-
#
-
# Should any of the +before_add+ callbacks throw an exception, the object does not get
-
# added to the collection. Same with the +before_remove+ callbacks; if an exception is
-
# thrown the object doesn't get removed.
-
#
-
# == Association extensions
-
#
-
# The proxy objects that control the access to associations can be extended through anonymous
-
# modules. This is especially beneficial for adding new finders, creators, and other
-
# factory-type methods that are only used as part of this association.
-
#
-
# class Account < ActiveRecord::Base
-
# has_many :people do
-
# def find_or_create_by_name(name)
-
# first_name, last_name = name.split(" ", 2)
-
# find_or_create_by_first_name_and_last_name(first_name, last_name)
-
# end
-
# end
-
# end
-
#
-
# person = Account.first.people.find_or_create_by_name("David Heinemeier Hansson")
-
# person.first_name # => "David"
-
# person.last_name # => "Heinemeier Hansson"
-
#
-
# If you need to share the same extensions between many associations, you can use a named
-
# extension module.
-
#
-
# module FindOrCreateByNameExtension
-
# def find_or_create_by_name(name)
-
# first_name, last_name = name.split(" ", 2)
-
# find_or_create_by_first_name_and_last_name(first_name, last_name)
-
# end
-
# end
-
#
-
# class Account < ActiveRecord::Base
-
# has_many :people, -> { extending FindOrCreateByNameExtension }
-
# end
-
#
-
# class Company < ActiveRecord::Base
-
# has_many :people, -> { extending FindOrCreateByNameExtension }
-
# end
-
#
-
# Some extensions can only be made to work with knowledge of the association's internals.
-
# Extensions can access relevant state using the following methods (where +items+ is the
-
# name of the association):
-
#
-
# * <tt>record.association(:items).owner</tt> - Returns the object the association is part of.
-
# * <tt>record.association(:items).reflection</tt> - Returns the reflection object that describes the association.
-
# * <tt>record.association(:items).target</tt> - Returns the associated object for +belongs_to+ and +has_one+, or
-
# the collection of associated objects for +has_many+ and +has_and_belongs_to_many+.
-
#
-
# However, inside the actual extension code, you will not have access to the <tt>record</tt> as
-
# above. In this case, you can access <tt>proxy_association</tt>. For example,
-
# <tt>record.association(:items)</tt> and <tt>record.items.proxy_association</tt> will return
-
# the same object, allowing you to make calls like <tt>proxy_association.owner</tt> inside
-
# association extensions.
-
#
-
# == Association Join Models
-
#
-
# Has Many associations can be configured with the <tt>:through</tt> option to use an
-
# explicit join model to retrieve the data. This operates similarly to a
-
# +has_and_belongs_to_many+ association. The advantage is that you're able to add validations,
-
# callbacks, and extra attributes on the join model. Consider the following schema:
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :authorships
-
# has_many :books, :through => :authorships
-
# end
-
#
-
# class Authorship < ActiveRecord::Base
-
# belongs_to :author
-
# belongs_to :book
-
# end
-
#
-
# @author = Author.first
-
# @author.authorships.collect { |a| a.book } # selects all books that the author's authorships belong to
-
# @author.books # selects all books by using the Authorship join model
-
#
-
# You can also go through a +has_many+ association on the join model:
-
#
-
# class Firm < ActiveRecord::Base
-
# has_many :clients
-
# has_many :invoices, :through => :clients
-
# end
-
#
-
# class Client < ActiveRecord::Base
-
# belongs_to :firm
-
# has_many :invoices
-
# end
-
#
-
# class Invoice < ActiveRecord::Base
-
# belongs_to :client
-
# end
-
#
-
# @firm = Firm.first
-
# @firm.clients.collect { |c| c.invoices }.flatten # select all invoices for all clients of the firm
-
# @firm.invoices # selects all invoices by going through the Client join model
-
#
-
# Similarly you can go through a +has_one+ association on the join model:
-
#
-
# class Group < ActiveRecord::Base
-
# has_many :users
-
# has_many :avatars, :through => :users
-
# end
-
#
-
# class User < ActiveRecord::Base
-
# belongs_to :group
-
# has_one :avatar
-
# end
-
#
-
# class Avatar < ActiveRecord::Base
-
# belongs_to :user
-
# end
-
#
-
# @group = Group.first
-
# @group.users.collect { |u| u.avatar }.compact # select all avatars for all users in the group
-
# @group.avatars # selects all avatars by going through the User join model.
-
#
-
# An important caveat with going through +has_one+ or +has_many+ associations on the
-
# join model is that these associations are *read-only*. For example, the following
-
# would not work following the previous example:
-
#
-
# @group.avatars << Avatar.new # this would work if User belonged_to Avatar rather than the other way around
-
# @group.avatars.delete(@group.avatars.last) # so would this
-
#
-
# If you are using a +belongs_to+ on the join model, it is a good idea to set the
-
# <tt>:inverse_of</tt> option on the +belongs_to+, which will mean that the following example
-
# works correctly (where <tt>tags</tt> is a +has_many+ <tt>:through</tt> association):
-
#
-
# @post = Post.first
-
# @tag = @post.tags.build :name => "ruby"
-
# @tag.save
-
#
-
# The last line ought to save the through record (a <tt>Taggable</tt>). This will only work if the
-
# <tt>:inverse_of</tt> is set:
-
#
-
# class Taggable < ActiveRecord::Base
-
# belongs_to :post
-
# belongs_to :tag, :inverse_of => :taggings
-
# end
-
#
-
# == Nested Associations
-
#
-
# You can actually specify *any* association with the <tt>:through</tt> option, including an
-
# association which has a <tt>:through</tt> option itself. For example:
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :posts
-
# has_many :comments, :through => :posts
-
# has_many :commenters, :through => :comments
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :comments
-
# end
-
#
-
# class Comment < ActiveRecord::Base
-
# belongs_to :commenter
-
# end
-
#
-
# @author = Author.first
-
# @author.commenters # => People who commented on posts written by the author
-
#
-
# An equivalent way of setting up this association this would be:
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :posts
-
# has_many :commenters, :through => :posts
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :comments
-
# has_many :commenters, :through => :comments
-
# end
-
#
-
# class Comment < ActiveRecord::Base
-
# belongs_to :commenter
-
# end
-
#
-
# When using nested association, you will not be able to modify the association because there
-
# is not enough information to know what modification to make. For example, if you tried to
-
# add a <tt>Commenter</tt> in the example above, there would be no way to tell how to set up the
-
# intermediate <tt>Post</tt> and <tt>Comment</tt> objects.
-
#
-
# == Polymorphic Associations
-
#
-
# Polymorphic associations on models are not restricted on what types of models they
-
# can be associated with. Rather, they specify an interface that a +has_many+ association
-
# must adhere to.
-
#
-
# class Asset < ActiveRecord::Base
-
# belongs_to :attachable, :polymorphic => true
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :assets, :as => :attachable # The :as option specifies the polymorphic interface to use.
-
# end
-
#
-
# @asset.attachable = @post
-
#
-
# This works by using a type column in addition to a foreign key to specify the associated
-
# record. In the Asset example, you'd need an +attachable_id+ integer column and an
-
# +attachable_type+ string column.
-
#
-
# Using polymorphic associations in combination with single table inheritance (STI) is
-
# a little tricky. In order for the associations to work as expected, ensure that you
-
# store the base model for the STI models in the type column of the polymorphic
-
# association. To continue with the asset example above, suppose there are guest posts
-
# and member posts that use the posts table for STI. In this case, there must be a +type+
-
# column in the posts table.
-
#
-
# class Asset < ActiveRecord::Base
-
# belongs_to :attachable, :polymorphic => true
-
#
-
# def attachable_type=(sType)
-
# super(sType.to_s.classify.constantize.base_class.to_s)
-
# end
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# # because we store "Post" in attachable_type now :dependent => :destroy will work
-
# has_many :assets, :as => :attachable, :dependent => :destroy
-
# end
-
#
-
# class GuestPost < Post
-
# end
-
#
-
# class MemberPost < Post
-
# end
-
#
-
# == Caching
-
#
-
# All of the methods are built on a simple caching principle that will keep the result
-
# of the last query around unless specifically instructed not to. The cache is even
-
# shared across methods to make it even cheaper to use the macro-added methods without
-
# worrying too much about performance at the first go.
-
#
-
# project.milestones # fetches milestones from the database
-
# project.milestones.size # uses the milestone cache
-
# project.milestones.empty? # uses the milestone cache
-
# project.milestones(true).size # fetches milestones from the database
-
# project.milestones # uses the milestone cache
-
#
-
# == Eager loading of associations
-
#
-
# Eager loading is a way to find objects of a certain class and a number of named associations.
-
# This is one of the easiest ways of to prevent the dreaded 1+N problem in which fetching 100
-
# posts that each need to display their author triggers 101 database queries. Through the
-
# use of eager loading, the 101 queries can be reduced to 2.
-
#
-
# class Post < ActiveRecord::Base
-
# belongs_to :author
-
# has_many :comments
-
# end
-
#
-
# Consider the following loop using the class above:
-
#
-
# Post.all.each do |post|
-
# puts "Post: " + post.title
-
# puts "Written by: " + post.author.name
-
# puts "Last comment on: " + post.comments.first.created_on
-
# end
-
#
-
# To iterate over these one hundred posts, we'll generate 201 database queries. Let's
-
# first just optimize it for retrieving the author:
-
#
-
# Post.includes(:author).each do |post|
-
#
-
# This references the name of the +belongs_to+ association that also used the <tt>:author</tt>
-
# symbol. After loading the posts, find will collect the +author_id+ from each one and load
-
# all the referenced authors with one query. Doing so will cut down the number of queries
-
# from 201 to 102.
-
#
-
# We can improve upon the situation further by referencing both associations in the finder with:
-
#
-
# Post.includes(:author, :comments).each do |post|
-
#
-
# This will load all comments with a single query. This reduces the total number of queries
-
# to 3. More generally the number of queries will be 1 plus the number of associations
-
# named (except if some of the associations are polymorphic +belongs_to+ - see below).
-
#
-
# To include a deep hierarchy of associations, use a hash:
-
#
-
# Post.includes(:author, {:comments => {:author => :gravatar}}).each do |post|
-
#
-
# That'll grab not only all the comments but all their authors and gravatar pictures.
-
# You can mix and match symbols, arrays and hashes in any combination to describe the
-
# associations you want to load.
-
#
-
# All of this power shouldn't fool you into thinking that you can pull out huge amounts
-
# of data with no performance penalty just because you've reduced the number of queries.
-
# The database still needs to send all the data to Active Record and it still needs to
-
# be processed. So it's no catch-all for performance problems, but it's a great way to
-
# cut down on the number of queries in a situation as the one described above.
-
#
-
# Since only one table is loaded at a time, conditions or orders cannot reference tables
-
# other than the main one. If this is the case Active Record falls back to the previously
-
# used LEFT OUTER JOIN based strategy. For example
-
#
-
# Post.includes([:author, :comments]).where(['comments.approved = ?', true]).all
-
#
-
# This will result in a single SQL query with joins along the lines of:
-
# <tt>LEFT OUTER JOIN comments ON comments.post_id = posts.id</tt> and
-
# <tt>LEFT OUTER JOIN authors ON authors.id = posts.author_id</tt>. Note that using conditions
-
# like this can have unintended consequences.
-
# In the above example posts with no approved comments are not returned at all, because
-
# the conditions apply to the SQL statement as a whole and not just to the association.
-
# You must disambiguate column references for this fallback to happen, for example
-
# <tt>:order => "author.name DESC"</tt> will work but <tt>:order => "name DESC"</tt> will not.
-
#
-
# If you do want eager load only some members of an association it is usually more natural
-
# to include an association which has conditions defined on it:
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :approved_comments, -> { where approved: true }, :class_name => 'Comment'
-
# end
-
#
-
# Post.includes(:approved_comments)
-
#
-
# This will load posts and eager load the +approved_comments+ association, which contains
-
# only those comments that have been approved.
-
#
-
# If you eager load an association with a specified <tt>:limit</tt> option, it will be ignored,
-
# returning all the associated objects:
-
#
-
# class Picture < ActiveRecord::Base
-
# has_many :most_recent_comments, -> { order('id DESC').limit(10) }, :class_name => 'Comment'
-
# end
-
#
-
# Picture.includes(:most_recent_comments).first.most_recent_comments # => returns all associated comments.
-
#
-
# Eager loading is supported with polymorphic associations.
-
#
-
# class Address < ActiveRecord::Base
-
# belongs_to :addressable, :polymorphic => true
-
# end
-
#
-
# A call that tries to eager load the addressable model
-
#
-
# Address.includes(:addressable)
-
#
-
# This will execute one query to load the addresses and load the addressables with one
-
# query per addressable type.
-
# For example if all the addressables are either of class Person or Company then a total
-
# of 3 queries will be executed. The list of addressable types to load is determined on
-
# the back of the addresses loaded. This is not supported if Active Record has to fallback
-
# to the previous implementation of eager loading and will raise ActiveRecord::EagerLoadPolymorphicError.
-
# The reason is that the parent model's type is a column value so its corresponding table
-
# name cannot be put in the +FROM+/+JOIN+ clauses of that query.
-
#
-
# == Table Aliasing
-
#
-
# Active Record uses table aliasing in the case that a table is referenced multiple times
-
# in a join. If a table is referenced only once, the standard table name is used. The
-
# second time, the table is aliased as <tt>#{reflection_name}_#{parent_table_name}</tt>.
-
# Indexes are appended for any more successive uses of the table name.
-
#
-
# Post.joins(:comments)
-
# # => SELECT ... FROM posts INNER JOIN comments ON ...
-
# Post.joins(:special_comments) # STI
-
# # => SELECT ... FROM posts INNER JOIN comments ON ... AND comments.type = 'SpecialComment'
-
# Post.joins(:comments, :special_comments) # special_comments is the reflection name, posts is the parent table name
-
# # => SELECT ... FROM posts INNER JOIN comments ON ... INNER JOIN comments special_comments_posts
-
#
-
# Acts as tree example:
-
#
-
# TreeMixin.joins(:children)
-
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
-
# TreeMixin.joins(:children => :parent)
-
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
-
# INNER JOIN parents_mixins ...
-
# TreeMixin.joins(:children => {:parent => :children})
-
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
-
# INNER JOIN parents_mixins ...
-
# INNER JOIN mixins childrens_mixins_2
-
#
-
# Has and Belongs to Many join tables use the same idea, but add a <tt>_join</tt> suffix:
-
#
-
# Post.joins(:categories)
-
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
-
# Post.joins(:categories => :posts)
-
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
-
# INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
-
# Post.joins(:categories => {:posts => :categories})
-
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
-
# INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
-
# INNER JOIN categories_posts categories_posts_join INNER JOIN categories categories_posts_2
-
#
-
# If you wish to specify your own custom joins using <tt>joins</tt> method, those table
-
# names will take precedence over the eager associations:
-
#
-
# Post.joins(:comments).joins("inner join comments ...")
-
# # => SELECT ... FROM posts INNER JOIN comments_posts ON ... INNER JOIN comments ...
-
# Post.joins(:comments, :special_comments).joins("inner join comments ...")
-
# # => SELECT ... FROM posts INNER JOIN comments comments_posts ON ...
-
# INNER JOIN comments special_comments_posts ...
-
# INNER JOIN comments ...
-
#
-
# Table aliases are automatically truncated according to the maximum length of table identifiers
-
# according to the specific database.
-
#
-
# == Modules
-
#
-
# By default, associations will look for objects within the current module scope. Consider:
-
#
-
# module MyApplication
-
# module Business
-
# class Firm < ActiveRecord::Base
-
# has_many :clients
-
# end
-
#
-
# class Client < ActiveRecord::Base; end
-
# end
-
# end
-
#
-
# When <tt>Firm#clients</tt> is called, it will in turn call
-
# <tt>MyApplication::Business::Client.find_all_by_firm_id(firm.id)</tt>.
-
# If you want to associate with a class in another module scope, this can be done by
-
# specifying the complete class name.
-
#
-
# module MyApplication
-
# module Business
-
# class Firm < ActiveRecord::Base; end
-
# end
-
#
-
# module Billing
-
# class Account < ActiveRecord::Base
-
# belongs_to :firm, :class_name => "MyApplication::Business::Firm"
-
# end
-
# end
-
# end
-
#
-
# == Bi-directional associations
-
#
-
# When you specify an association there is usually an association on the associated model
-
# that specifies the same relationship in reverse. For example, with the following models:
-
#
-
# class Dungeon < ActiveRecord::Base
-
# has_many :traps
-
# has_one :evil_wizard
-
# end
-
#
-
# class Trap < ActiveRecord::Base
-
# belongs_to :dungeon
-
# end
-
#
-
# class EvilWizard < ActiveRecord::Base
-
# belongs_to :dungeon
-
# end
-
#
-
# The +traps+ association on +Dungeon+ and the +dungeon+ association on +Trap+ are
-
# the inverse of each other and the inverse of the +dungeon+ association on +EvilWizard+
-
# is the +evil_wizard+ association on +Dungeon+ (and vice-versa). By default,
-
# Active Record doesn't know anything about these inverse relationships and so no object
-
# loading optimization is possible. For example:
-
#
-
# d = Dungeon.first
-
# t = d.traps.first
-
# d.level == t.dungeon.level # => true
-
# d.level = 10
-
# d.level == t.dungeon.level # => false
-
#
-
# The +Dungeon+ instances +d+ and <tt>t.dungeon</tt> in the above example refer to
-
# the same object data from the database, but are actually different in-memory copies
-
# of that data. Specifying the <tt>:inverse_of</tt> option on associations lets you tell
-
# Active Record about inverse relationships and it will optimise object loading. For
-
# example, if we changed our model definitions to:
-
#
-
# class Dungeon < ActiveRecord::Base
-
# has_many :traps, :inverse_of => :dungeon
-
# has_one :evil_wizard, :inverse_of => :dungeon
-
# end
-
#
-
# class Trap < ActiveRecord::Base
-
# belongs_to :dungeon, :inverse_of => :traps
-
# end
-
#
-
# class EvilWizard < ActiveRecord::Base
-
# belongs_to :dungeon, :inverse_of => :evil_wizard
-
# end
-
#
-
# Then, from our code snippet above, +d+ and <tt>t.dungeon</tt> are actually the same
-
# in-memory instance and our final <tt>d.level == t.dungeon.level</tt> will return +true+.
-
#
-
# There are limitations to <tt>:inverse_of</tt> support:
-
#
-
# * does not work with <tt>:through</tt> associations.
-
# * does not work with <tt>:polymorphic</tt> associations.
-
# * for +belongs_to+ associations +has_many+ inverse associations are ignored.
-
#
-
# == Deleting from associations
-
#
-
# === Dependent associations
-
#
-
# +has_many+, +has_one+ and +belongs_to+ associations support the <tt>:dependent</tt> option.
-
# This allows you to specify that associated records should be deleted when the owner is
-
# deleted.
-
#
-
# For example:
-
#
-
# class Author
-
# has_many :posts, :dependent => :destroy
-
# end
-
# Author.find(1).destroy # => Will destroy all of the author's posts, too
-
#
-
# The <tt>:dependent</tt> option can have different values which specify how the deletion
-
# is done. For more information, see the documentation for this option on the different
-
# specific association types. When no option is given, the behaviour is to do nothing
-
# with the associated records when destroying a record.
-
#
-
# Note that <tt>:dependent</tt> is implemented using Rails' callback
-
# system, which works by processing callbacks in order. Therefore, other
-
# callbacks declared either before or after the <tt>:dependent</tt> option
-
# can affect what it does.
-
#
-
# === Delete or destroy?
-
#
-
# +has_many+ and +has_and_belongs_to_many+ associations have the methods <tt>destroy</tt>,
-
# <tt>delete</tt>, <tt>destroy_all</tt> and <tt>delete_all</tt>.
-
#
-
# For +has_and_belongs_to_many+, <tt>delete</tt> and <tt>destroy</tt> are the same: they
-
# cause the records in the join table to be removed.
-
#
-
# For +has_many+, <tt>destroy</tt> will always call the <tt>destroy</tt> method of the
-
# record(s) being removed so that callbacks are run. However <tt>delete</tt> will either
-
# do the deletion according to the strategy specified by the <tt>:dependent</tt> option, or
-
# if no <tt>:dependent</tt> option is given, then it will follow the default strategy.
-
# The default strategy is <tt>:nullify</tt> (set the foreign keys to <tt>nil</tt>), except for
-
# +has_many+ <tt>:through</tt>, where the default strategy is <tt>delete_all</tt> (delete
-
# the join records, without running their callbacks).
-
#
-
# There is also a <tt>clear</tt> method which is the same as <tt>delete_all</tt>, except that
-
# it returns the association rather than the records which have been deleted.
-
#
-
# === What gets deleted?
-
#
-
# There is a potential pitfall here: +has_and_belongs_to_many+ and +has_many+ <tt>:through</tt>
-
# associations have records in join tables, as well as the associated records. So when we
-
# call one of these deletion methods, what exactly should be deleted?
-
#
-
# The answer is that it is assumed that deletion on an association is about removing the
-
# <i>link</i> between the owner and the associated object(s), rather than necessarily the
-
# associated objects themselves. So with +has_and_belongs_to_many+ and +has_many+
-
# <tt>:through</tt>, the join records will be deleted, but the associated records won't.
-
#
-
# This makes sense if you think about it: if you were to call <tt>post.tags.delete(Tag.find_by_name('food'))</tt>
-
# you would want the 'food' tag to be unlinked from the post, rather than for the tag itself
-
# to be removed from the database.
-
#
-
# However, there are examples where this strategy doesn't make sense. For example, suppose
-
# a person has many projects, and each project has many tasks. If we deleted one of a person's
-
# tasks, we would probably not want the project to be deleted. In this scenario, the delete method
-
# won't actually work: it can only be used if the association on the join model is a
-
# +belongs_to+. In other situations you are expected to perform operations directly on
-
# either the associated records or the <tt>:through</tt> association.
-
#
-
# With a regular +has_many+ there is no distinction between the "associated records"
-
# and the "link", so there is only one choice for what gets deleted.
-
#
-
# With +has_and_belongs_to_many+ and +has_many+ <tt>:through</tt>, if you want to delete the
-
# associated records themselves, you can always do something along the lines of
-
# <tt>person.tasks.each(&:destroy)</tt>.
-
#
-
# == Type safety with <tt>ActiveRecord::AssociationTypeMismatch</tt>
-
#
-
# If you attempt to assign an object to an association that doesn't match the inferred
-
# or specified <tt>:class_name</tt>, you'll get an <tt>ActiveRecord::AssociationTypeMismatch</tt>.
-
#
-
# == Options
-
#
-
# All of the association macros can be specialized through options. This makes cases
-
# more complex than the simple and guessable ones possible.
-
1
module ClassMethods
-
# Specifies a one-to-many association. The following methods for retrieval and query of
-
# collections of associated objects will be added:
-
#
-
# [collection(force_reload = false)]
-
# Returns an array of all the associated objects.
-
# An empty array is returned if none are found.
-
# [collection<<(object, ...)]
-
# Adds one or more objects to the collection by setting their foreign keys to the collection's primary key.
-
# Note that this operation instantly fires update sql without waiting for the save or update call on the
-
# parent object.
-
# [collection.delete(object, ...)]
-
# Removes one or more objects from the collection by setting their foreign keys to +NULL+.
-
# Objects will be in addition destroyed if they're associated with <tt>:dependent => :destroy</tt>,
-
# and deleted if they're associated with <tt>:dependent => :delete_all</tt>.
-
#
-
# If the <tt>:through</tt> option is used, then the join records are deleted (rather than
-
# nullified) by default, but you can specify <tt>:dependent => :destroy</tt> or
-
# <tt>:dependent => :nullify</tt> to override this.
-
# [collection.destroy(object, ...)]
-
# Removes one or more objects from the collection by running <tt>destroy</tt> on
-
# each record, regardless of any dependent option, ensuring callbacks are run.
-
#
-
# If the <tt>:through</tt> option is used, then the join records are destroyed
-
# instead, not the objects themselves.
-
# [collection=objects]
-
# Replaces the collections content by deleting and adding objects as appropriate. If the <tt>:through</tt>
-
# option is true callbacks in the join models are triggered except destroy callbacks, since deletion is
-
# direct.
-
# [collection_singular_ids]
-
# Returns an array of the associated objects' ids
-
# [collection_singular_ids=ids]
-
# Replace the collection with the objects identified by the primary keys in +ids+. This
-
# method loads the models and calls <tt>collection=</tt>. See above.
-
# [collection.clear]
-
# Removes every object from the collection. This destroys the associated objects if they
-
# are associated with <tt>:dependent => :destroy</tt>, deletes them directly from the
-
# database if <tt>:dependent => :delete_all</tt>, otherwise sets their foreign keys to +NULL+.
-
# If the <tt>:through</tt> option is true no destroy callbacks are invoked on the join models.
-
# Join models are directly deleted.
-
# [collection.empty?]
-
# Returns +true+ if there are no associated objects.
-
# [collection.size]
-
# Returns the number of associated objects.
-
# [collection.find(...)]
-
# Finds an associated object according to the same rules as ActiveRecord::Base.find.
-
# [collection.exists?(...)]
-
# Checks whether an associated object with the given conditions exists.
-
# Uses the same rules as ActiveRecord::Base.exists?.
-
# [collection.build(attributes = {}, ...)]
-
# Returns one or more new objects of the collection type that have been instantiated
-
# with +attributes+ and linked to this object through a foreign key, but have not yet
-
# been saved.
-
# [collection.create(attributes = {})]
-
# Returns a new object of the collection type that has been instantiated
-
# with +attributes+, linked to this object through a foreign key, and that has already
-
# been saved (if it passed the validation). *Note*: This only works if the base model
-
# already exists in the DB, not if it is a new (unsaved) record!
-
#
-
# (*Note*: +collection+ is replaced with the symbol passed as the first argument, so
-
# <tt>has_many :clients</tt> would add among others <tt>clients.empty?</tt>.)
-
#
-
# === Example
-
#
-
# Example: A Firm class declares <tt>has_many :clients</tt>, which will add:
-
# * <tt>Firm#clients</tt> (similar to <tt>Clients.all :conditions => ["firm_id = ?", id]</tt>)
-
# * <tt>Firm#clients<<</tt>
-
# * <tt>Firm#clients.delete</tt>
-
# * <tt>Firm#clients.destroy</tt>
-
# * <tt>Firm#clients=</tt>
-
# * <tt>Firm#client_ids</tt>
-
# * <tt>Firm#client_ids=</tt>
-
# * <tt>Firm#clients.clear</tt>
-
# * <tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>)
-
# * <tt>Firm#clients.size</tt> (similar to <tt>Client.count "firm_id = #{id}"</tt>)
-
# * <tt>Firm#clients.find</tt> (similar to <tt>Client.find(id, :conditions => "firm_id = #{id}")</tt>)
-
# * <tt>Firm#clients.exists?(:name => 'ACME')</tt> (similar to <tt>Client.exists?(:name => 'ACME', :firm_id => firm.id)</tt>)
-
# * <tt>Firm#clients.build</tt> (similar to <tt>Client.new("firm_id" => id)</tt>)
-
# * <tt>Firm#clients.create</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save; c</tt>)
-
# The declaration can also include an options hash to specialize the behavior of the association.
-
#
-
# === Options
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>has_many :products</tt> will by default be linked
-
# to the Product class, but if the real class name is SpecialProduct, you'll have to
-
# specify it with this option.
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_many+
-
# association will use "person_id" as the default <tt>:foreign_key</tt>.
-
# [:primary_key]
-
# Specify the method that returns the primary key used for the association. By default this is +id+.
-
# [:dependent]
-
# Controls what happens to the associated objects when
-
# their owner is destroyed. Note that these are implemented as
-
# callbacks, and Rails executes callbacks in order. Therefore, other
-
# similar callbacks may affect the :dependent behavior, and the
-
# :dependent behavior may affect other callbacks.
-
#
-
# * <tt>:destroy</tt> causes all the associated objects to also be destroyed
-
# * <tt>:delete_all</tt> causes all the asssociated objects to be deleted directly from the database (so callbacks will not execute)
-
# * <tt>:nullify</tt> causes the foreign keys to be set to +NULL+. Callbacks are not executed.
-
# * <tt>:restrict_with_exception</tt> causes an exception to be raised if there are any associated records
-
# * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there are any associated objects
-
#
-
# If using with the <tt>:through</tt> option, the association on the join model must be
-
# a +belongs_to+, and the records which get deleted are the join records, rather than
-
# the associated records.
-
# [:counter_cache]
-
# This option can be used to configure a custom named <tt>:counter_cache.</tt> You only need this option,
-
# when you customized the name of your <tt>:counter_cache</tt> on the <tt>belongs_to</tt> association.
-
# [:as]
-
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
-
# [:through]
-
# Specifies an association through which to perform the query. This can be any other type
-
# of association, including other <tt>:through</tt> associations. Options for <tt>:class_name</tt>,
-
# <tt>:primary_key</tt> and <tt>:foreign_key</tt> are ignored, as the association uses the
-
# source reflection.
-
#
-
# If the association on the join model is a +belongs_to+, the collection can be modified
-
# and the records on the <tt>:through</tt> model will be automatically created and removed
-
# as appropriate. Otherwise, the collection is read-only, so you should manipulate the
-
# <tt>:through</tt> association directly.
-
#
-
# If you are going to modify the association (rather than just read from it), then it is
-
# a good idea to set the <tt>:inverse_of</tt> option on the source association on the
-
# join model. This allows associated records to be built which will automatically create
-
# the appropriate join model records when they are saved. (See the 'Association Join Models'
-
# section above.)
-
# [:source]
-
# Specifies the source association name used by <tt>has_many :through</tt> queries.
-
# Only use it if the name cannot be inferred from the association.
-
# <tt>has_many :subscribers, :through => :subscriptions</tt> will look for either <tt>:subscribers</tt> or
-
# <tt>:subscriber</tt> on Subscription, unless a <tt>:source</tt> is given.
-
# [:source_type]
-
# Specifies type of the source association used by <tt>has_many :through</tt> queries where the source
-
# association is a polymorphic +belongs_to+.
-
# [:validate]
-
# If +false+, don't validate the associated objects when saving the parent object. true by default.
-
# [:autosave]
-
# If true, always save the associated objects or destroy them if marked for destruction,
-
# when saving the parent object. If false, never save or destroy the associated objects.
-
# By default, only save associated objects that are new records. This option is implemented as a
-
# before_save callback. Because callbacks are run in the order they are defined, associated objects
-
# may need to be explicitly saved in any user-defined before_save callbacks.
-
#
-
# Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
-
# [:inverse_of]
-
# Specifies the name of the <tt>belongs_to</tt> association on the associated object
-
# that is the inverse of this <tt>has_many</tt> association. Does not work in combination
-
# with <tt>:through</tt> or <tt>:as</tt> options.
-
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
-
#
-
# Option examples:
-
# has_many :comments, -> { order "posted_on" }
-
# has_many :comments, -> { includes :author }
-
# has_many :people, -> { where("deleted = 0").order("name") }, class_name: "Person"
-
# has_many :tracks, -> { order "position" }, dependent: :destroy
-
# has_many :comments, dependent: :nullify
-
# has_many :tags, as: :taggable
-
# has_many :reports, -> { readonly }
-
# has_many :subscribers, through: :subscriptions, source: :user
-
1
def has_many(name, scope = nil, options = {}, &extension)
-
Builder::HasMany.build(self, name, scope, options, &extension)
-
end
-
-
# Specifies a one-to-one association with another class. This method should only be used
-
# if the other class contains the foreign key. If the current class contains the foreign key,
-
# then you should use +belongs_to+ instead. See also ActiveRecord::Associations::ClassMethods's overview
-
# on when to use has_one and when to use belongs_to.
-
#
-
# The following methods for retrieval and query of a single associated object will be added:
-
#
-
# [association(force_reload = false)]
-
# Returns the associated object. +nil+ is returned if none is found.
-
# [association=(associate)]
-
# Assigns the associate object, extracts the primary key, sets it as the foreign key,
-
# and saves the associate object.
-
# [build_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+ and linked to this object through a foreign key, but has not
-
# yet been saved.
-
# [create_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+, linked to this object through a foreign key, and that
-
# has already been saved (if it passed the validation).
-
# [create_association!(attributes = {})]
-
# Does the same as <tt>create_association</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
-
# if the record is invalid.
-
#
-
# (+association+ is replaced with the symbol passed as the first argument, so
-
# <tt>has_one :manager</tt> would add among others <tt>manager.nil?</tt>.)
-
#
-
# === Example
-
#
-
# An Account class declares <tt>has_one :beneficiary</tt>, which will add:
-
# * <tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.first(:conditions => "account_id = #{id}")</tt>)
-
# * <tt>Account#beneficiary=(beneficiary)</tt> (similar to <tt>beneficiary.account_id = account.id; beneficiary.save</tt>)
-
# * <tt>Account#build_beneficiary</tt> (similar to <tt>Beneficiary.new("account_id" => id)</tt>)
-
# * <tt>Account#create_beneficiary</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save; b</tt>)
-
# * <tt>Account#create_beneficiary!</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save!; b</tt>)
-
#
-
# === Options
-
#
-
# The declaration can also include an options hash to specialize the behavior of the association.
-
#
-
# Options are:
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>has_one :manager</tt> will by default be linked to the Manager class, but
-
# if the real class name is Person, you'll have to specify it with this option.
-
# [:dependent]
-
# Controls what happens to the associated object when
-
# its owner is destroyed:
-
#
-
# * <tt>:destroy</tt> causes the associated object to also be destroyed
-
# * <tt>:delete</tt> causes the asssociated object to be deleted directly from the database (so callbacks will not execute)
-
# * <tt>:nullify</tt> causes the foreign key to be set to +NULL+. Callbacks are not executed.
-
# * <tt>:restrict_with_exception</tt> causes an exception to be raised if there is an associated record
-
# * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there is an associated object
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_one+ association
-
# will use "person_id" as the default <tt>:foreign_key</tt>.
-
# [:primary_key]
-
# Specify the method that returns the primary key used for the association. By default this is +id+.
-
# [:as]
-
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
-
# [:through]
-
# Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt>,
-
# <tt>:primary_key</tt>, and <tt>:foreign_key</tt> are ignored, as the association uses the
-
# source reflection. You can only use a <tt>:through</tt> query through a <tt>has_one</tt>
-
# or <tt>belongs_to</tt> association on the join model.
-
# [:source]
-
# Specifies the source association name used by <tt>has_one :through</tt> queries.
-
# Only use it if the name cannot be inferred from the association.
-
# <tt>has_one :favorite, :through => :favorites</tt> will look for a
-
# <tt>:favorite</tt> on Favorite, unless a <tt>:source</tt> is given.
-
# [:source_type]
-
# Specifies type of the source association used by <tt>has_one :through</tt> queries where the source
-
# association is a polymorphic +belongs_to+.
-
# [:validate]
-
# If +false+, don't validate the associated object when saving the parent object. +false+ by default.
-
# [:autosave]
-
# If true, always save the associated object or destroy it if marked for destruction,
-
# when saving the parent object. If false, never save or destroy the associated object.
-
# By default, only save the associated object if it's a new record.
-
#
-
# Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
-
# [:inverse_of]
-
# Specifies the name of the <tt>belongs_to</tt> association on the associated object
-
# that is the inverse of this <tt>has_one</tt> association. Does not work in combination
-
# with <tt>:through</tt> or <tt>:as</tt> options.
-
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
-
#
-
# Option examples:
-
# has_one :credit_card, :dependent => :destroy # destroys the associated credit card
-
# has_one :credit_card, :dependent => :nullify # updates the associated records foreign
-
# # key value to NULL rather than destroying it
-
# has_one :last_comment, -> { order 'posted_on' }, :class_name => "Comment"
-
# has_one :project_manager, -> { where role: 'project_manager' }, :class_name => "Person"
-
# has_one :attachment, as: :attachable
-
# has_one :boss, readonly: :true
-
# has_one :club, through: :membership
-
# has_one :primary_address, -> { where primary: true }, through: :addressables, source: :addressable
-
1
def has_one(name, scope = nil, options = {})
-
Builder::HasOne.build(self, name, scope, options)
-
end
-
-
# Specifies a one-to-one association with another class. This method should only be used
-
# if this class contains the foreign key. If the other class contains the foreign key,
-
# then you should use +has_one+ instead. See also ActiveRecord::Associations::ClassMethods's overview
-
# on when to use +has_one+ and when to use +belongs_to+.
-
#
-
# Methods will be added for retrieval and query for a single associated object, for which
-
# this object holds an id:
-
#
-
# [association(force_reload = false)]
-
# Returns the associated object. +nil+ is returned if none is found.
-
# [association=(associate)]
-
# Assigns the associate object, extracts the primary key, and sets it as the foreign key.
-
# [build_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+ and linked to this object through a foreign key, but has not yet been saved.
-
# [create_association(attributes = {})]
-
# Returns a new object of the associated type that has been instantiated
-
# with +attributes+, linked to this object through a foreign key, and that
-
# has already been saved (if it passed the validation).
-
# [create_association!(attributes = {})]
-
# Does the same as <tt>create_association</tt>, but raises <tt>ActiveRecord::RecordInvalid</tt>
-
# if the record is invalid.
-
#
-
# (+association+ is replaced with the symbol passed as the first argument, so
-
# <tt>belongs_to :author</tt> would add among others <tt>author.nil?</tt>.)
-
#
-
# === Example
-
#
-
# A Post class declares <tt>belongs_to :author</tt>, which will add:
-
# * <tt>Post#author</tt> (similar to <tt>Author.find(author_id)</tt>)
-
# * <tt>Post#author=(author)</tt> (similar to <tt>post.author_id = author.id</tt>)
-
# * <tt>Post#build_author</tt> (similar to <tt>post.author = Author.new</tt>)
-
# * <tt>Post#create_author</tt> (similar to <tt>post.author = Author.new; post.author.save; post.author</tt>)
-
# * <tt>Post#create_author!</tt> (similar to <tt>post.author = Author.new; post.author.save!; post.author</tt>)
-
# The declaration can also include an options hash to specialize the behavior of the association.
-
#
-
# === Options
-
#
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>belongs_to :author</tt> will by default be linked to the Author class, but
-
# if the real class name is Person, you'll have to specify it with this option.
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of the association with an "_id" suffix. So a class that defines a <tt>belongs_to :person</tt>
-
# association will use "person_id" as the default <tt>:foreign_key</tt>. Similarly,
-
# <tt>belongs_to :favorite_person, :class_name => "Person"</tt> will use a foreign key
-
# of "favorite_person_id".
-
# [:foreign_type]
-
# Specify the column used to store the associated object's type, if this is a polymorphic
-
# association. By default this is guessed to be the name of the association with a "_type"
-
# suffix. So a class that defines a <tt>belongs_to :taggable, :polymorphic => true</tt>
-
# association will use "taggable_type" as the default <tt>:foreign_type</tt>.
-
# [:primary_key]
-
# Specify the method that returns the primary key of associated object used for the association.
-
# By default this is id.
-
# [:dependent]
-
# If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
-
# <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method.
-
# This option should not be specified when <tt>belongs_to</tt> is used in conjunction with
-
# a <tt>has_many</tt> relationship on another class because of the potential to leave
-
# orphaned records behind.
-
# [:counter_cache]
-
# Caches the number of belonging objects on the associate class through the use of +increment_counter+
-
# and +decrement_counter+. The counter cache is incremented when an object of this
-
# class is created and decremented when it's destroyed. This requires that a column
-
# named <tt>#{table_name}_count</tt> (such as +comments_count+ for a belonging Comment class)
-
# is used on the associate class (such as a Post class) - that is the migration for
-
# <tt>#{table_name}_count</tt> is created on the associate class (such that Post.comments_count will
-
# return the count cached, see note below). You can also specify a custom counter
-
# cache column by providing a column name instead of a +true+/+false+ value to this
-
# option (e.g., <tt>:counter_cache => :my_custom_counter</tt>.)
-
# Note: Specifying a counter cache will add it to that model's list of readonly attributes
-
# using +attr_readonly+.
-
# [:polymorphic]
-
# Specify this association is a polymorphic association by passing +true+.
-
# Note: If you've enabled the counter cache, then you may want to add the counter cache attribute
-
# to the +attr_readonly+ list in the associated classes (e.g. <tt>class Post; attr_readonly :comments_count; end</tt>).
-
# [:validate]
-
# If +false+, don't validate the associated objects when saving the parent object. +false+ by default.
-
# [:autosave]
-
# If true, always save the associated object or destroy it if marked for destruction, when
-
# saving the parent object.
-
# If false, never save or destroy the associated object.
-
# By default, only save the associated object if it's a new record.
-
#
-
# Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
-
# [:touch]
-
# If true, the associated object will be touched (the updated_at/on attributes set to now)
-
# when this record is either saved or destroyed. If you specify a symbol, that attribute
-
# will be updated with the current time in addition to the updated_at/on attribute.
-
# [:inverse_of]
-
# Specifies the name of the <tt>has_one</tt> or <tt>has_many</tt> association on the associated
-
# object that is the inverse of this <tt>belongs_to</tt> association. Does not work in
-
# combination with the <tt>:polymorphic</tt> options.
-
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
-
#
-
# Option examples:
-
# belongs_to :firm, foreign_key: "client_of"
-
# belongs_to :person, primary_key: "name", foreign_key: "person_name"
-
# belongs_to :author, class_name: "Person", foreign_key: "author_id"
-
# belongs_to :valid_coupon, ->(o) { where "discounts > #{o.payments_count}" },
-
# class_name: "Coupon", foreign_key: "coupon_id"
-
# belongs_to :attachable, polymorphic: true
-
# belongs_to :project, readonly: true
-
# belongs_to :post, counter_cache: true
-
# belongs_to :company, touch: true
-
# belongs_to :company, touch: :employees_last_updated_at
-
1
def belongs_to(name, scope = nil, options = {})
-
Builder::BelongsTo.build(self, name, scope, options)
-
end
-
-
# Specifies a many-to-many relationship with another class. This associates two classes via an
-
# intermediate join table. Unless the join table is explicitly specified as an option, it is
-
# guessed using the lexical order of the class names. So a join between Developer and Project
-
# will give the default join table name of "developers_projects" because "D" precedes "P" alphabetically.
-
# Note that this precedence is calculated using the <tt><</tt> operator for String. This
-
# means that if the strings are of different lengths, and the strings are equal when compared
-
# up to the shortest length, then the longer string is considered of higher
-
# lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers"
-
# to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes",
-
# but it in fact generates a join table name of "paper_boxes_papers". Be aware of this caveat, and use the
-
# custom <tt>:join_table</tt> option if you need to.
-
#
-
# The join table should not have a primary key or a model associated with it. You must manually generate the
-
# join table with a migration such as this:
-
#
-
# class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration
-
# def change
-
# create_table :developers_projects, :id => false do |t|
-
# t.integer :developer_id
-
# t.integer :project_id
-
# end
-
# end
-
# end
-
#
-
# It's also a good idea to add indexes to each of those columns to speed up the joins process.
-
# However, in MySQL it is advised to add a compound index for both of the columns as MySQL only
-
# uses one index per table during the lookup.
-
#
-
# Adds the following methods for retrieval and query:
-
#
-
# [collection(force_reload = false)]
-
# Returns an array of all the associated objects.
-
# An empty array is returned if none are found.
-
# [collection<<(object, ...)]
-
# Adds one or more objects to the collection by creating associations in the join table
-
# (<tt>collection.push</tt> and <tt>collection.concat</tt> are aliases to this method).
-
# Note that this operation instantly fires update sql without waiting for the save or update call on the
-
# parent object.
-
# [collection.delete(object, ...)]
-
# Removes one or more objects from the collection by removing their associations from the join table.
-
# This does not destroy the objects.
-
# [collection.destroy(object, ...)]
-
# Removes one or more objects from the collection by running destroy on each association in the join table, overriding any dependent option.
-
# This does not destroy the objects.
-
# [collection=objects]
-
# Replaces the collection's content by deleting and adding objects as appropriate.
-
# [collection_singular_ids]
-
# Returns an array of the associated objects' ids.
-
# [collection_singular_ids=ids]
-
# Replace the collection by the objects identified by the primary keys in +ids+.
-
# [collection.clear]
-
# Removes every object from the collection. This does not destroy the objects.
-
# [collection.empty?]
-
# Returns +true+ if there are no associated objects.
-
# [collection.size]
-
# Returns the number of associated objects.
-
# [collection.find(id)]
-
# Finds an associated object responding to the +id+ and that
-
# meets the condition that it has to be associated with this object.
-
# Uses the same rules as ActiveRecord::Base.find.
-
# [collection.exists?(...)]
-
# Checks whether an associated object with the given conditions exists.
-
# Uses the same rules as ActiveRecord::Base.exists?.
-
# [collection.build(attributes = {})]
-
# Returns a new object of the collection type that has been instantiated
-
# with +attributes+ and linked to this object through the join table, but has not yet been saved.
-
# [collection.create(attributes = {})]
-
# Returns a new object of the collection type that has been instantiated
-
# with +attributes+, linked to this object through the join table, and that has already been
-
# saved (if it passed the validation).
-
#
-
# (+collection+ is replaced with the symbol passed as the first argument, so
-
# <tt>has_and_belongs_to_many :categories</tt> would add among others <tt>categories.empty?</tt>.)
-
#
-
# === Example
-
#
-
# A Developer class declares <tt>has_and_belongs_to_many :projects</tt>, which will add:
-
# * <tt>Developer#projects</tt>
-
# * <tt>Developer#projects<<</tt>
-
# * <tt>Developer#projects.delete</tt>
-
# * <tt>Developer#projects.destroy</tt>
-
# * <tt>Developer#projects=</tt>
-
# * <tt>Developer#project_ids</tt>
-
# * <tt>Developer#project_ids=</tt>
-
# * <tt>Developer#projects.clear</tt>
-
# * <tt>Developer#projects.empty?</tt>
-
# * <tt>Developer#projects.size</tt>
-
# * <tt>Developer#projects.find(id)</tt>
-
# * <tt>Developer#projects.exists?(...)</tt>
-
# * <tt>Developer#projects.build</tt> (similar to <tt>Project.new("developer_id" => id)</tt>)
-
# * <tt>Developer#projects.create</tt> (similar to <tt>c = Project.new("developer_id" => id); c.save; c</tt>)
-
# The declaration may include an options hash to specialize the behavior of the association.
-
#
-
# === Options
-
#
-
# [:class_name]
-
# Specify the class name of the association. Use it only if that name can't be inferred
-
# from the association name. So <tt>has_and_belongs_to_many :projects</tt> will by default be linked to the
-
# Project class, but if the real class name is SuperProject, you'll have to specify it with this option.
-
# [:join_table]
-
# Specify the name of the join table if the default based on lexical order isn't what you want.
-
# <b>WARNING:</b> If you're overwriting the table name of either class, the +table_name+ method
-
# MUST be declared underneath any +has_and_belongs_to_many+ declaration in order to work.
-
# [:foreign_key]
-
# Specify the foreign key used for the association. By default this is guessed to be the name
-
# of this class in lower-case and "_id" suffixed. So a Person class that makes
-
# a +has_and_belongs_to_many+ association to Project will use "person_id" as the
-
# default <tt>:foreign_key</tt>.
-
# [:association_foreign_key]
-
# Specify the foreign key used for the association on the receiving side of the association.
-
# By default this is guessed to be the name of the associated class in lower-case and "_id" suffixed.
-
# So if a Person class makes a +has_and_belongs_to_many+ association to Project,
-
# the association will use "project_id" as the default <tt>:association_foreign_key</tt>.
-
# [:readonly]
-
# If true, all the associated objects are readonly through the association.
-
# [:validate]
-
# If +false+, don't validate the associated objects when saving the parent object. +true+ by default.
-
# [:autosave]
-
# If true, always save the associated objects or destroy them if marked for destruction, when
-
# saving the parent object.
-
# If false, never save or destroy the associated objects.
-
# By default, only save associated objects that are new records.
-
#
-
# Note that <tt>accepts_nested_attributes_for</tt> sets <tt>:autosave</tt> to <tt>true</tt>.
-
#
-
# Option examples:
-
# has_and_belongs_to_many :projects
-
# has_and_belongs_to_many :projects, -> { includes :milestones, :manager }
-
# has_and_belongs_to_many :nations, class_name: "Country"
-
# has_and_belongs_to_many :categories, join_table: "prods_cats"
-
# has_and_belongs_to_many :categories, -> { readonly }
-
1
def has_and_belongs_to_many(name, scope = nil, options = {}, &extension)
-
Builder::HasAndBelongsToMany.build(self, name, scope, options, &extension)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord::Associations::Builder
-
1
class Association #:nodoc:
-
1
class << self
-
1
attr_accessor :valid_options
-
end
-
-
1
self.valid_options = [:class_name, :foreign_key, :validate]
-
-
1
attr_reader :model, :name, :scope, :options, :reflection
-
-
1
def self.build(*args, &block)
-
new(*args, &block).build
-
end
-
-
1
def initialize(model, name, scope, options)
-
@model = model
-
@name = name
-
-
if scope.is_a?(Hash)
-
@scope = nil
-
@options = scope
-
else
-
@scope = scope
-
@options = options
-
end
-
-
if @scope && @scope.arity == 0
-
prev_scope = @scope
-
@scope = proc { instance_exec(&prev_scope) }
-
end
-
end
-
-
1
def mixin
-
@model.generated_feature_methods
-
end
-
-
2
include Module.new { def build; end }
-
-
1
def build
-
validate_options
-
define_accessors
-
configure_dependency if options[:dependent]
-
@reflection = model.create_reflection(macro, name, scope, options, model)
-
super # provides an extension point
-
@reflection
-
end
-
-
1
def macro
-
raise NotImplementedError
-
end
-
-
1
def valid_options
-
Association.valid_options
-
end
-
-
1
def validate_options
-
options.assert_valid_keys(valid_options)
-
end
-
-
1
def define_accessors
-
define_readers
-
define_writers
-
end
-
-
1
def define_readers
-
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}(*args)
-
association(:#{name}).reader(*args)
-
end
-
CODE
-
end
-
-
1
def define_writers
-
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}=(value)
-
association(:#{name}).writer(value)
-
end
-
CODE
-
end
-
-
1
def configure_dependency
-
unless valid_dependent_options.include? options[:dependent]
-
raise ArgumentError, "The :dependent option must be one of #{valid_dependent_options}, but is :#{options[:dependent]}"
-
end
-
-
if options[:dependent] == :restrict
-
ActiveSupport::Deprecation.warn(
-
"The :restrict option is deprecated. Please use :restrict_with_exception instead, which " \
-
"provides the same functionality."
-
)
-
end
-
-
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{macro}_dependent_for_#{name}
-
association(:#{name}).handle_dependency
-
end
-
CODE
-
-
model.before_destroy "#{macro}_dependent_for_#{name}"
-
end
-
-
1
def valid_dependent_options
-
raise NotImplementedError
-
end
-
end
-
end
-
1
require 'active_record/associations'
-
-
1
module ActiveRecord::Associations::Builder
-
1
class CollectionAssociation < Association #:nodoc:
-
-
1
CALLBACKS = [:before_add, :after_add, :before_remove, :after_remove]
-
-
1
def valid_options
-
super + [:table_name, :finder_sql, :counter_sql, :before_add, :after_add, :before_remove, :after_remove]
-
end
-
-
1
attr_reader :block_extension, :extension_module
-
-
1
def initialize(*args, &extension)
-
super(*args)
-
@block_extension = extension
-
end
-
-
1
def build
-
show_deprecation_warnings
-
wrap_block_extension
-
reflection = super
-
CALLBACKS.each { |callback_name| define_callback(callback_name) }
-
reflection
-
end
-
-
1
def writable?
-
true
-
end
-
-
1
def show_deprecation_warnings
-
[:finder_sql, :counter_sql].each do |name|
-
if options.include? name
-
ActiveSupport::Deprecation.warn("The :#{name} association option is deprecated. Please find an alternative (such as using scopes).")
-
end
-
end
-
end
-
-
1
def wrap_block_extension
-
if block_extension
-
@extension_module = mod = Module.new(&block_extension)
-
silence_warnings do
-
model.parent.const_set(extension_module_name, mod)
-
end
-
-
prev_scope = @scope
-
-
if prev_scope
-
@scope = proc { |owner| instance_exec(owner, &prev_scope).extending(mod) }
-
else
-
@scope = proc { extending(mod) }
-
end
-
end
-
end
-
-
1
def extension_module_name
-
@extension_module_name ||= "#{model.name.demodulize}#{name.to_s.camelize}AssociationExtension"
-
end
-
-
1
def define_callback(callback_name)
-
full_callback_name = "#{callback_name}_for_#{name}"
-
-
# TODO : why do i need method_defined? I think its because of the inheritance chain
-
model.class_attribute full_callback_name.to_sym unless model.method_defined?(full_callback_name)
-
model.send("#{full_callback_name}=", Array(options[callback_name.to_sym]))
-
end
-
-
1
def define_readers
-
super
-
-
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name.to_s.singularize}_ids
-
association(:#{name}).ids_reader
-
end
-
CODE
-
end
-
-
1
def define_writers
-
super
-
-
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name.to_s.singularize}_ids=(ids)
-
association(:#{name}).ids_writer(ids)
-
end
-
CODE
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Associations
-
# Association proxies in Active Record are middlemen between the object that
-
# holds the association, known as the <tt>@owner</tt>, and the actual associated
-
# object, known as the <tt>@target</tt>. The kind of association any proxy is
-
# about is available in <tt>@reflection</tt>. That's an instance of the class
-
# ActiveRecord::Reflection::AssociationReflection.
-
#
-
# For example, given
-
#
-
# class Blog < ActiveRecord::Base
-
# has_many :posts
-
# end
-
#
-
# blog = Blog.first
-
#
-
# the association proxy in <tt>blog.posts</tt> has the object in +blog+ as
-
# <tt>@owner</tt>, the collection of its posts as <tt>@target</tt>, and
-
# the <tt>@reflection</tt> object represents a <tt>:has_many</tt> macro.
-
#
-
# This class delegates unknown methods to <tt>@target</tt> via
-
# <tt>method_missing</tt>.
-
#
-
# The <tt>@target</tt> object is not \loaded until needed. For example,
-
#
-
# blog.posts.count
-
#
-
# is computed directly through SQL and does not trigger by itself the
-
# instantiation of the actual post records.
-
1
class CollectionProxy < Relation
-
1
delegate(*(ActiveRecord::Calculations.public_instance_methods - [:count]), to: :scope)
-
-
1
def initialize(association) #:nodoc:
-
@association = association
-
super association.klass, association.klass.arel_table
-
merge! association.scope(nullify: false)
-
end
-
-
1
def target
-
@association.target
-
end
-
-
1
def load_target
-
@association.load_target
-
end
-
-
# Returns +true+ if the association has been loaded, otherwise +false+.
-
#
-
# person.pets.loaded? # => false
-
# person.pets
-
# person.pets.loaded? # => true
-
1
def loaded?
-
@association.loaded?
-
end
-
-
# Works in two ways.
-
#
-
# *First:* Specify a subset of fields to be selected from the result set.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.select(:name)
-
# # => [
-
# # #<Pet id: nil, name: "Fancy-Fancy">,
-
# # #<Pet id: nil, name: "Spook">,
-
# # #<Pet id: nil, name: "Choo-Choo">
-
# # ]
-
#
-
# person.pets.select([:id, :name])
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy">,
-
# # #<Pet id: 2, name: "Spook">,
-
# # #<Pet id: 3, name: "Choo-Choo">
-
# # ]
-
#
-
# Be careful because this also means you’re initializing a model
-
# object with only the fields that you’ve selected. If you attempt
-
# to access a field that is not in the initialized record you’ll
-
# receive:
-
#
-
# person.pets.select(:name).first.person_id
-
# # => ActiveModel::MissingAttributeError: missing attribute: person_id
-
#
-
# *Second:* You can pass a block so it can be used just like Array#select.
-
# This build an array of objects from the database for the scope,
-
# converting them into an array and iterating through them using
-
# Array#select.
-
#
-
# person.pets.select { |pet| pet.name =~ /oo/ }
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.select(:name) { |pet| pet.name =~ /oo/ }
-
# # => [
-
# # #<Pet id: 2, name: "Spook">,
-
# # #<Pet id: 3, name: "Choo-Choo">
-
# # ]
-
1
def select(select = nil, &block)
-
@association.select(select, &block)
-
end
-
-
# Finds an object in the collection responding to the +id+. Uses the same
-
# rules as <tt>ActiveRecord::Base.find</tt>. Returns <tt>ActiveRecord::RecordNotFound</tt>
-
# error if the object can not be found.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.find(1) # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
-
# person.pets.find(4) # => ActiveRecord::RecordNotFound: Couldn't find Pet with id=4
-
#
-
# person.pets.find(2) { |pet| pet.name.downcase! }
-
# # => #<Pet id: 2, name: "fancy-fancy", person_id: 1>
-
#
-
# person.pets.find(2, 3)
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
1
def find(*args, &block)
-
@association.find(*args, &block)
-
end
-
-
# Returns the first record, or the first +n+ records, from the collection.
-
# If the collection is empty, the first form returns +nil+, and the second
-
# form returns an empty array.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.first # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
-
#
-
# person.pets.first(2)
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>
-
# # ]
-
#
-
# another_person_without.pets # => []
-
# another_person_without.pets.first # => nil
-
# another_person_without.pets.first(3) # => []
-
1
def first(*args)
-
@association.first(*args)
-
end
-
-
# Returns the last record, or the last +n+ records, from the collection.
-
# If the collection is empty, the first form returns +nil+, and the second
-
# form returns an empty array.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.last # => #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
#
-
# person.pets.last(2)
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# another_person_without.pets # => []
-
# another_person_without.pets.last # => nil
-
# another_person_without.pets.last(3) # => []
-
1
def last(*args)
-
@association.last(*args)
-
end
-
-
# Returns a new object of the collection type that has been instantiated
-
# with +attributes+ and linked to this object, but have not yet been saved.
-
# You can pass an array of attributes hashes, this will return an array
-
# with the new objects.
-
#
-
# class Person
-
# has_many :pets
-
# end
-
#
-
# person.pets.build
-
# # => #<Pet id: nil, name: nil, person_id: 1>
-
#
-
# person.pets.build(name: 'Fancy-Fancy')
-
# # => #<Pet id: nil, name: "Fancy-Fancy", person_id: 1>
-
#
-
# person.pets.build([{name: 'Spook'}, {name: 'Choo-Choo'}, {name: 'Brain'}])
-
# # => [
-
# # #<Pet id: nil, name: "Spook", person_id: 1>,
-
# # #<Pet id: nil, name: "Choo-Choo", person_id: 1>,
-
# # #<Pet id: nil, name: "Brain", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 5 # size of the collection
-
# person.pets.count # => 0 # count from database
-
1
def build(attributes = {}, &block)
-
@association.build(attributes, &block)
-
end
-
-
# Returns a new object of the collection type that has been instantiated with
-
# attributes, linked to this object and that has already been saved (if it
-
# passes the validations).
-
#
-
# class Person
-
# has_many :pets
-
# end
-
#
-
# person.pets.create(name: 'Fancy-Fancy')
-
# # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
-
#
-
# person.pets.create([{name: 'Spook'}, {name: 'Choo-Choo'}])
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 3
-
# person.pets.count # => 3
-
#
-
# person.pets.find(1, 2, 3)
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
1
def create(attributes = {}, &block)
-
@association.create(attributes, &block)
-
end
-
-
# Like +create+, except that if the record is invalid, raises an exception.
-
#
-
# class Person
-
# has_many :pets
-
# end
-
#
-
# class Pet
-
# validates :name, presence: true
-
# end
-
#
-
# person.pets.create!(name: nil)
-
# # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
-
1
def create!(attributes = {}, &block)
-
@association.create!(attributes, &block)
-
end
-
-
# Add one or more records to the collection by setting their foreign keys
-
# to the association's primary key. Since << flattens its argument list and
-
# inserts each record, +push+ and +concat+ behave identically. Returns +self+
-
# so method calls may be chained.
-
#
-
# class Person < ActiveRecord::Base
-
# pets :has_many
-
# end
-
#
-
# person.pets.size # => 0
-
# person.pets.concat(Pet.new(name: 'Fancy-Fancy'))
-
# person.pets.concat(Pet.new(name: 'Spook'), Pet.new(name: 'Choo-Choo'))
-
# person.pets.size # => 3
-
#
-
# person.id # => 1
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.concat([Pet.new(name: 'Brain'), Pet.new(name: 'Benny')])
-
# person.pets.size # => 5
-
1
def concat(*records)
-
@association.concat(*records)
-
end
-
-
# Replace this collection with +other_array+. This will perform a diff
-
# and delete/add only records that have changed.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [#<Pet id: 1, name: "Gorby", group: "cats", person_id: 1>]
-
#
-
# other_pets = [Pet.new(name: 'Puff', group: 'celebrities']
-
#
-
# person.pets.replace(other_pets)
-
#
-
# person.pets
-
# # => [#<Pet id: 2, name: "Puff", group: "celebrities", person_id: 1>]
-
#
-
# If the supplied array has an incorrect association type, it raises
-
# an <tt>ActiveRecord::AssociationTypeMismatch</tt> error:
-
#
-
# person.pets.replace(["doo", "ggie", "gaga"])
-
# # => ActiveRecord::AssociationTypeMismatch: Pet expected, got String
-
1
def replace(other_array)
-
@association.replace(other_array)
-
end
-
-
# Deletes all the records from the collection. For +has_many+ associations,
-
# the deletion is done according to the strategy specified by the <tt>:dependent</tt>
-
# option. Returns an array with the deleted records.
-
#
-
# If no <tt>:dependent</tt> option is given, then it will follow the
-
# default strategy. The default strategy is <tt>:nullify</tt>. This
-
# sets the foreign keys to <tt>NULL</tt>. For, +has_many+ <tt>:through</tt>,
-
# the default strategy is +delete_all+.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets # dependent: :nullify option by default
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete_all
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 0
-
# person.pets # => []
-
#
-
# Pet.find(1, 2, 3)
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: nil>,
-
# # #<Pet id: 2, name: "Spook", person_id: nil>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: nil>
-
# # ]
-
#
-
# If it is set to <tt>:destroy</tt> all the objects from the collection
-
# are removed by calling their +destroy+ method. See +destroy+ for more
-
# information.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets, dependent: :destroy
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete_all
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# Pet.find(1, 2, 3)
-
# # => ActiveRecord::RecordNotFound
-
#
-
# If it is set to <tt>:delete_all</tt>, all the objects are deleted
-
# *without* calling their +destroy+ method.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets, dependent: :delete_all
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete_all
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# Pet.find(1, 2, 3)
-
# # => ActiveRecord::RecordNotFound
-
1
def delete_all
-
@association.delete_all
-
end
-
-
# Deletes the records of the collection directly from the database.
-
# This will _always_ remove the records ignoring the +:dependent+
-
# option.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy_all
-
#
-
# person.pets.size # => 0
-
# person.pets # => []
-
#
-
# Pet.find(1) # => Couldn't find Pet with id=1
-
1
def destroy_all
-
@association.destroy_all
-
end
-
-
# Deletes the +records+ supplied and removes them from the collection. For
-
# +has_many+ associations, the deletion is done according to the strategy
-
# specified by the <tt>:dependent</tt> option. Returns an array with the
-
# deleted records.
-
#
-
# If no <tt>:dependent</tt> option is given, then it will follow the default
-
# strategy. The default strategy is <tt>:nullify</tt>. This sets the foreign
-
# keys to <tt>NULL</tt>. For, +has_many+ <tt>:through</tt>, the default
-
# strategy is +delete_all+.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets # dependent: :nullify option by default
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete(Pet.find(1))
-
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
-
#
-
# person.pets.size # => 2
-
# person.pets
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# Pet.find(1)
-
# # => #<Pet id: 1, name: "Fancy-Fancy", person_id: nil>
-
#
-
# If it is set to <tt>:destroy</tt> all the +records+ are removed by calling
-
# their +destroy+ method. See +destroy+ for more information.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets, dependent: :destroy
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete(Pet.find(1), Pet.find(3))
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 1
-
# person.pets
-
# # => [#<Pet id: 2, name: "Spook", person_id: 1>]
-
#
-
# Pet.find(1, 3)
-
# # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (1, 3)
-
#
-
# If it is set to <tt>:delete_all</tt>, all the +records+ are deleted
-
# *without* calling their +destroy+ method.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets, dependent: :delete_all
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete(Pet.find(1))
-
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
-
#
-
# person.pets.size # => 2
-
# person.pets
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# Pet.find(1)
-
# # => ActiveRecord::RecordNotFound: Couldn't find Pet with id=1
-
#
-
# You can pass +Fixnum+ or +String+ values, it finds the records
-
# responding to the +id+ and executes delete on them.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.delete("1")
-
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
-
#
-
# person.pets.delete(2, 3)
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
1
def delete(*records)
-
@association.delete(*records)
-
end
-
-
# Destroys the +records+ supplied and removes them from the collection.
-
# This method will _always_ remove record from the database ignoring
-
# the +:dependent+ option. Returns an array with the removed records.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy(Pet.find(1))
-
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
-
#
-
# person.pets.size # => 2
-
# person.pets
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy(Pet.find(2), Pet.find(3))
-
# # => [
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 0
-
# person.pets # => []
-
#
-
# Pet.find(1, 2, 3) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (1, 2, 3)
-
#
-
# You can pass +Fixnum+ or +String+ values, it finds the records
-
# responding to the +id+ and then deletes them from the database.
-
#
-
# person.pets.size # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 4, name: "Benny", person_id: 1>,
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy("4")
-
# # => #<Pet id: 4, name: "Benny", person_id: 1>
-
#
-
# person.pets.size # => 2
-
# person.pets
-
# # => [
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# person.pets.destroy(5, 6)
-
# # => [
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 0
-
# person.pets # => []
-
#
-
# Pet.find(4, 5, 6) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (4, 5, 6)
-
1
def destroy(*records)
-
@association.destroy(*records)
-
end
-
-
# Specifies whether the records should be unique or not.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.select(:name)
-
# # => [
-
# # #<Pet name: "Fancy-Fancy">,
-
# # #<Pet name: "Fancy-Fancy">
-
# # ]
-
#
-
# person.pets.select(:name).uniq
-
# # => [#<Pet name: "Fancy-Fancy">]
-
1
def uniq
-
@association.uniq
-
end
-
-
# Count all records using SQL.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.count # => 3
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
1
def count(column_name = nil, options = {})
-
@association.count(column_name, options)
-
end
-
-
# Returns the size of the collection. If the collection hasn't been loaded,
-
# it executes a <tt>SELECT COUNT(*)</tt> query.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 3
-
# # executes something like SELECT COUNT(*) FROM "pets" WHERE "pets"."person_id" = 1
-
#
-
# person.pets # This will execute a SELECT * FROM query
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
#
-
# person.pets.size # => 3
-
# # Because the collection is already loaded, this will behave like
-
# # collection.size and no SQL count query is executed.
-
1
def size
-
@association.size
-
end
-
-
# Returns the size of the collection calling +size+ on the target.
-
# If the collection has been already loaded, +length+ and +size+ are
-
# equivalent.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.length # => 3
-
# # executes something like SELECT "pets".* FROM "pets" WHERE "pets"."person_id" = 1
-
#
-
# # Because the collection is loaded, you can
-
# # call the collection with no additional queries:
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
1
def length
-
@association.length
-
end
-
-
# Returns +true+ if the collection is empty.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.count # => 1
-
# person.pets.empty? # => false
-
#
-
# person.pets.delete_all
-
#
-
# person.pets.count # => 0
-
# person.pets.empty? # => true
-
1
def empty?
-
@association.empty?
-
end
-
-
# Returns +true+ if the collection is not empty.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.count # => 0
-
# person.pets.any? # => false
-
#
-
# person.pets << Pet.new(name: 'Snoop')
-
# person.pets.count # => 0
-
# person.pets.any? # => true
-
#
-
# You can also pass a block to define criteria. The behaviour
-
# is the same, it returns true if the collection based on the
-
# criteria is not empty.
-
#
-
# person.pets
-
# # => [#<Pet name: "Snoop", group: "dogs">]
-
#
-
# person.pets.any? do |pet|
-
# pet.group == 'cats'
-
# end
-
# # => false
-
#
-
# person.pets.any? do |pet|
-
# pet.group == 'dogs'
-
# end
-
# # => true
-
1
def any?(&block)
-
@association.any?(&block)
-
end
-
-
# Returns true if the collection has more than one record.
-
# Equivalent to <tt>collection.size > 1</tt>.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.count #=> 1
-
# person.pets.many? #=> false
-
#
-
# person.pets << Pet.new(name: 'Snoopy')
-
# person.pets.count #=> 2
-
# person.pets.many? #=> true
-
#
-
# You can also pass a block to define criteria. The
-
# behaviour is the same, it returns true if the collection
-
# based on the criteria has more than one record.
-
#
-
# person.pets
-
# # => [
-
# # #<Pet name: "Gorby", group: "cats">,
-
# # #<Pet name: "Puff", group: "cats">,
-
# # #<Pet name: "Snoop", group: "dogs">
-
# # ]
-
#
-
# person.pets.many? do |pet|
-
# pet.group == 'dogs'
-
# end
-
# # => false
-
#
-
# person.pets.many? do |pet|
-
# pet.group == 'cats'
-
# end
-
# # => true
-
1
def many?(&block)
-
@association.many?(&block)
-
end
-
-
# Returns +true+ if the given object is present in the collection.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets # => [#<Pet id: 20, name: "Snoop">]
-
#
-
# person.pets.include?(Pet.find(20)) # => true
-
# person.pets.include?(Pet.find(21)) # => false
-
1
def include?(record)
-
@association.include?(record)
-
end
-
-
1
alias_method :new, :build
-
-
1
def proxy_association
-
@association
-
end
-
-
# We don't want this object to be put on the scoping stack, because
-
# that could create an infinite loop where we call an @association
-
# method, which gets the current scope, which is this object, which
-
# delegates to @association, and so on.
-
1
def scoping
-
@association.scope.scoping { yield }
-
end
-
-
# Returns a <tt>Relation</tt> object for the records in this association
-
1
def scope
-
association = @association
-
-
@association.scope.extending! do
-
define_method(:proxy_association) { association }
-
end
-
end
-
-
# :nodoc:
-
1
alias spawn scope
-
-
# Equivalent to <tt>Array#==</tt>. Returns +true+ if the two arrays
-
# contain the same number of elements and if each element is equal
-
# to the corresponding element in the other array, otherwise returns
-
# +false+.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>
-
# # ]
-
#
-
# other = person.pets.to_ary
-
#
-
# person.pets == other
-
# # => true
-
#
-
# other = [Pet.new(id: 1), Pet.new(id: 2)]
-
#
-
# person.pets == other
-
# # => false
-
1
def ==(other)
-
load_target == other
-
end
-
-
# Returns a new array of objects from the collection. If the collection
-
# hasn't been loaded, it fetches the records from the database.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets
-
# # => [
-
# # #<Pet id: 4, name: "Benny", person_id: 1>,
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# other_pets = person.pets.to_ary
-
# # => [
-
# # #<Pet id: 4, name: "Benny", person_id: 1>,
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
#
-
# other_pets.replace([Pet.new(name: 'BooGoo')])
-
#
-
# other_pets
-
# # => [#<Pet id: nil, name: "BooGoo", person_id: 1>]
-
#
-
# person.pets
-
# # This is not affected by replace
-
# # => [
-
# # #<Pet id: 4, name: "Benny", person_id: 1>,
-
# # #<Pet id: 5, name: "Brain", person_id: 1>,
-
# # #<Pet id: 6, name: "Boss", person_id: 1>
-
# # ]
-
1
def to_ary
-
load_target.dup
-
end
-
1
alias_method :to_a, :to_ary
-
-
# Adds one or more +records+ to the collection by setting their foreign keys
-
# to the association‘s primary key. Returns +self+, so several appends may be
-
# chained together.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets.size # => 0
-
# person.pets << Pet.new(name: 'Fancy-Fancy')
-
# person.pets << [Pet.new(name: 'Spook'), Pet.new(name: 'Choo-Choo')]
-
# person.pets.size # => 3
-
#
-
# person.id # => 1
-
# person.pets
-
# # => [
-
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
-
# # #<Pet id: 2, name: "Spook", person_id: 1>,
-
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
-
# # ]
-
1
def <<(*records)
-
proxy_association.concat(records) && self
-
end
-
1
alias_method :push, :<<
-
-
# Equivalent to +delete_all+. The difference is that returns +self+, instead
-
# of an array with the deleted objects, so methods can be chained. See
-
# +delete_all+ for more information.
-
1
def clear
-
delete_all
-
self
-
end
-
-
# Reloads the collection from the database. Returns +self+.
-
# Equivalent to <tt>collection(true)</tt>.
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :pets
-
# end
-
#
-
# person.pets # fetches pets from the database
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
#
-
# person.pets # uses the pets cache
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
#
-
# person.pets.reload # fetches pets from the database
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
#
-
# person.pets(true) # fetches pets from the database
-
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
-
1
def reload
-
proxy_association.reload
-
self
-
end
-
end
-
end
-
end
-
-
1
module ActiveRecord
-
1
module AttributeAssignment
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::DeprecatedMassAssignmentSecurity
-
1
include ActiveModel::ForbiddenAttributesProtection
-
-
# Allows you to set all the attributes by passing in a hash of attributes with
-
# keys matching the attribute names (which again matches the column names).
-
#
-
# If the passed hash responds to <tt>permitted?</tt> method and the return value
-
# of this method is +false+ an <tt>ActiveModel::ForbiddenAttributesError</tt>
-
# exception is raised.
-
1
def assign_attributes(new_attributes)
-
return if new_attributes.blank?
-
-
attributes = new_attributes.stringify_keys
-
multi_parameter_attributes = []
-
nested_parameter_attributes = []
-
-
attributes = sanitize_for_mass_assignment(attributes)
-
-
attributes.each do |k, v|
-
if k.include?("(")
-
multi_parameter_attributes << [ k, v ]
-
elsif v.is_a?(Hash)
-
nested_parameter_attributes << [ k, v ]
-
else
-
_assign_attribute(k, v)
-
end
-
end
-
-
assign_nested_parameter_attributes(nested_parameter_attributes) unless nested_parameter_attributes.empty?
-
assign_multiparameter_attributes(multi_parameter_attributes) unless multi_parameter_attributes.empty?
-
end
-
-
1
alias attributes= assign_attributes
-
-
1
private
-
-
1
def _assign_attribute(k, v)
-
public_send("#{k}=", v)
-
rescue NoMethodError
-
if respond_to?("#{k}=")
-
raise
-
else
-
raise UnknownAttributeError, "unknown attribute: #{k}"
-
end
-
end
-
-
# Assign any deferred nested attributes after the base attributes have been set.
-
1
def assign_nested_parameter_attributes(pairs)
-
pairs.each { |k, v| _assign_attribute(k, v) }
-
end
-
-
# Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done
-
# by calling new on the column type or aggregation type (through composed_of) object with these parameters.
-
# So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate
-
# written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the
-
# parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum and
-
# f for Float. If all the values for a given attribute are empty, the attribute will be set to +nil+.
-
1
def assign_multiparameter_attributes(pairs)
-
execute_callstack_for_multiparameter_attributes(
-
extract_callstack_for_multiparameter_attributes(pairs)
-
)
-
end
-
-
1
def execute_callstack_for_multiparameter_attributes(callstack)
-
errors = []
-
callstack.each do |name, values_with_empty_parameters|
-
begin
-
send("#{name}=", MultiparameterAttribute.new(self, name, values_with_empty_parameters).read_value)
-
rescue => ex
-
errors << AttributeAssignmentError.new("error on assignment #{values_with_empty_parameters.values.inspect} to #{name} (#{ex.message})", ex, name)
-
end
-
end
-
unless errors.empty?
-
error_descriptions = errors.map { |ex| ex.message }.join(",")
-
raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes [#{error_descriptions}]"
-
end
-
end
-
-
1
def extract_callstack_for_multiparameter_attributes(pairs)
-
attributes = { }
-
-
pairs.each do |(multiparameter_name, value)|
-
attribute_name = multiparameter_name.split("(").first
-
attributes[attribute_name] ||= {}
-
-
parameter_value = value.empty? ? nil : type_cast_attribute_value(multiparameter_name, value)
-
attributes[attribute_name][find_parameter_position(multiparameter_name)] ||= parameter_value
-
end
-
-
attributes
-
end
-
-
1
def type_cast_attribute_value(multiparameter_name, value)
-
multiparameter_name =~ /\([0-9]*([if])\)/ ? value.send("to_" + $1) : value
-
end
-
-
1
def find_parameter_position(multiparameter_name)
-
multiparameter_name.scan(/\(([0-9]*).*\)/).first.first.to_i
-
end
-
-
1
class MultiparameterAttribute #:nodoc:
-
1
attr_reader :object, :name, :values, :column
-
-
1
def initialize(object, name, values)
-
@object = object
-
@name = name
-
@values = values
-
end
-
-
1
def read_value
-
return if values.values.compact.empty?
-
-
@column = object.class.reflect_on_aggregation(name.to_sym) || object.column_for_attribute(name)
-
klass = column.klass
-
-
if klass == Time
-
read_time
-
elsif klass == Date
-
read_date
-
else
-
read_other(klass)
-
end
-
end
-
-
1
private
-
-
1
def instantiate_time_object(set_values)
-
if object.class.send(:create_time_zone_conversion_attribute?, name, column)
-
Time.zone.local(*set_values)
-
else
-
Time.time_with_datetime_fallback(object.class.default_timezone, *set_values)
-
end
-
end
-
-
1
def read_time
-
# If column is a :time (and not :date or :timestamp) there is no need to validate if
-
# there are year/month/day fields
-
if column.type == :time
-
# if the column is a time set the values to their defaults as January 1, 1970, but only if they're nil
-
{ 1 => 1970, 2 => 1, 3 => 1 }.each do |key,value|
-
values[key] ||= value
-
end
-
else
-
# else column is a timestamp, so if Date bits were not provided, error
-
validate_missing_parameters!([1,2,3])
-
-
# If Date bits were provided but blank, then return nil
-
return if blank_date_parameter?
-
end
-
-
max_position = extract_max_param(6)
-
set_values = values.values_at(*(1..max_position))
-
# If Time bits are not there, then default to 0
-
(3..5).each { |i| set_values[i] = set_values[i].presence || 0 }
-
instantiate_time_object(set_values)
-
end
-
-
1
def read_date
-
return if blank_date_parameter?
-
set_values = values.values_at(1,2,3)
-
begin
-
Date.new(*set_values)
-
rescue ArgumentError # if Date.new raises an exception on an invalid date
-
instantiate_time_object(set_values).to_date # we instantiate Time object and convert it back to a date thus using Time's logic in handling invalid dates
-
end
-
end
-
-
1
def read_other(klass)
-
max_position = extract_max_param
-
positions = (1..max_position)
-
validate_missing_parameters!(positions)
-
-
set_values = values.values_at(*positions)
-
klass.new(*set_values)
-
end
-
-
# Checks whether some blank date parameter exists. Note that this is different
-
# than the validate_missing_parameters! method, since it just checks for blank
-
# positions instead of missing ones, and does not raise in case one blank position
-
# exists. The caller is responsible to handle the case of this returning true.
-
1
def blank_date_parameter?
-
(1..3).any? { |position| values[position].blank? }
-
end
-
-
# If some position is not provided, it errors out a missing parameter exception.
-
1
def validate_missing_parameters!(positions)
-
if missing_parameter = positions.detect { |position| !values.key?(position) }
-
raise ArgumentError.new("Missing Parameter - #{name}(#{missing_parameter})")
-
end
-
end
-
-
1
def extract_max_param(upper_cap = 100)
-
[values.keys.max, upper_cap].min
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/enumerable'
-
-
1
module ActiveRecord
-
# = Active Record Attribute Methods
-
1
module AttributeMethods
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::AttributeMethods
-
-
1
included do
-
1
include Read
-
1
include Write
-
1
include BeforeTypeCast
-
1
include Query
-
1
include PrimaryKey
-
1
include TimeZoneConversion
-
1
include Dirty
-
1
include Serialization
-
end
-
-
1
module ClassMethods
-
# Generates all the attribute related methods for columns in the database
-
# accessors, mutators and query methods.
-
1
def define_attribute_methods # :nodoc:
-
# Use a mutex; we don't want two thread simaltaneously trying to define
-
# attribute methods.
-
@attribute_methods_mutex.synchronize do
-
return if attribute_methods_generated?
-
superclass.define_attribute_methods unless self == base_class
-
super(column_names)
-
@attribute_methods_generated = true
-
end
-
end
-
-
1
def attribute_methods_generated? # :nodoc:
-
5
@attribute_methods_generated ||= false
-
end
-
-
1
def undefine_attribute_methods # :nodoc:
-
5
super if attribute_methods_generated?
-
5
@attribute_methods_generated = false
-
end
-
-
# Raises a <tt>ActiveRecord::DangerousAttributeError</tt> exception when an
-
# \Active \Record method is defined in the model, otherwise +false+.
-
#
-
# class Person < ActiveRecord::Base
-
# def save
-
# 'already defined by Active Record'
-
# end
-
# end
-
#
-
# Person.instance_method_already_implemented?(:save)
-
# # => ActiveRecord::DangerousAttributeError: save is defined by ActiveRecord
-
#
-
# Person.instance_method_already_implemented?(:name)
-
# # => false
-
1
def instance_method_already_implemented?(method_name)
-
if dangerous_attribute_method?(method_name)
-
raise DangerousAttributeError, "#{method_name} is defined by ActiveRecord"
-
end
-
-
if superclass == Base
-
super
-
else
-
# If B < A and A defines its own attribute method, then we don't want to overwrite that.
-
defined = method_defined_within?(method_name, superclass, superclass.generated_attribute_methods)
-
defined && !ActiveRecord::Base.method_defined?(method_name) || super
-
end
-
end
-
-
# A method name is 'dangerous' if it is already defined by Active Record, but
-
# not by any ancestors. (So 'puts' is not dangerous but 'save' is.)
-
1
def dangerous_attribute_method?(name) # :nodoc:
-
method_defined_within?(name, Base)
-
end
-
-
1
def method_defined_within?(name, klass, sup = klass.superclass) # :nodoc:
-
if klass.method_defined?(name) || klass.private_method_defined?(name)
-
if sup.method_defined?(name) || sup.private_method_defined?(name)
-
klass.instance_method(name).owner != sup.instance_method(name).owner
-
else
-
true
-
end
-
else
-
false
-
end
-
end
-
-
# Returns +true+ if +attribute+ is an attribute method and table exists,
-
# +false+ otherwise.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# Person.attribute_method?('name') # => true
-
# Person.attribute_method?(:age=) # => true
-
# Person.attribute_method?(:nothing) # => false
-
1
def attribute_method?(attribute)
-
super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, '')))
-
end
-
-
# Returns an array of column names as strings if it's not an abstract class and
-
# table exists. Otherwise it returns an empty array.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# Person.attribute_names
-
# # => ["id", "created_at", "updated_at", "name", "age"]
-
1
def attribute_names
-
@attribute_names ||= if !abstract_class? && table_exists?
-
column_names
-
else
-
[]
-
end
-
end
-
end
-
-
# If we haven't generated any methods yet, generate them, then
-
# see if we've created the method we're looking for.
-
1
def method_missing(method, *args, &block) # :nodoc:
-
unless self.class.attribute_methods_generated?
-
self.class.define_attribute_methods
-
-
if respond_to_without_attributes?(method)
-
send(method, *args, &block)
-
else
-
super
-
end
-
else
-
super
-
end
-
end
-
-
1
def attribute_missing(match, *args, &block) # :nodoc:
-
if self.class.columns_hash[match.attr_name]
-
ActiveSupport::Deprecation.warn(
-
"The method `#{match.method_name}', matching the attribute `#{match.attr_name}' has " \
-
"dispatched through method_missing. This shouldn't happen, because `#{match.attr_name}' " \
-
"is a column of the table. If this error has happened through normal usage of Active " \
-
"Record (rather than through your own code or external libraries), please report it as " \
-
"a bug."
-
)
-
end
-
-
super
-
end
-
-
# A Person object with a name attribute can ask <tt>person.respond_to?(:name)</tt>,
-
# <tt>person.respond_to?(:name=)</tt>, and <tt>person.respond_to?(:name?)</tt>
-
# which will all return +true+. It also define the attribute methods if they have
-
# not been generated.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person.respond_to(:name) # => true
-
# person.respond_to(:name=) # => true
-
# person.respond_to(:name?) # => true
-
# person.respond_to('age') # => true
-
# person.respond_to('age=') # => true
-
# person.respond_to('age?') # => true
-
# person.respond_to(:nothing) # => false
-
1
def respond_to?(name, include_private = false)
-
self.class.define_attribute_methods unless self.class.attribute_methods_generated?
-
super
-
end
-
-
# Returns +true+ if the given attribute is in the attributes hash, otherwise +false+.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person.has_attribute?(:name) # => true
-
# person.has_attribute?('age') # => true
-
# person.has_attribute?(:nothing) # => false
-
1
def has_attribute?(attr_name)
-
@attributes.has_key?(attr_name.to_s)
-
end
-
-
# Returns an array of names for the attributes available on this object.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person.attribute_names
-
# # => ["id", "created_at", "updated_at", "name", "age"]
-
1
def attribute_names
-
@attributes.keys
-
end
-
-
# Returns a hash of all the attributes with their names as keys and the values of the attributes as values.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.create(name: 'Francesco', age: 22)
-
# person.attributes
-
# # => {"id"=>3, "created_at"=>Sun, 21 Oct 2012 04:53:04, "updated_at"=>Sun, 21 Oct 2012 04:53:04, "name"=>"Francesco", "age"=>22}
-
1
def attributes
-
attribute_names.each_with_object({}) { |name, attrs|
-
attrs[name] = read_attribute(name)
-
}
-
end
-
-
# Returns an <tt>#inspect</tt>-like string for the value of the
-
# attribute +attr_name+. String attributes are truncated upto 50
-
# characters, and Date and Time attributes are returned in the
-
# <tt>:db</tt> format. Other attributes return the value of
-
# <tt>#inspect</tt> without modification.
-
#
-
# person = Person.create!(name: 'David Heinemeier Hansson ' * 3)
-
#
-
# person.attribute_for_inspect(:name)
-
# # => "\"David Heinemeier Hansson David Heinemeier Hansson D...\""
-
#
-
# person.attribute_for_inspect(:created_at)
-
# # => "\"2012-10-22 00:15:07\""
-
1
def attribute_for_inspect(attr_name)
-
value = read_attribute(attr_name)
-
-
if value.is_a?(String) && value.length > 50
-
"#{value[0..50]}...".inspect
-
elsif value.is_a?(Date) || value.is_a?(Time)
-
%("#{value.to_s(:db)}")
-
else
-
value.inspect
-
end
-
end
-
-
# Returns +true+ if the specified +attribute+ has been set by the user or by a
-
# database load and is neither +nil+ nor <tt>empty?</tt> (the latter only applies
-
# to objects that respond to <tt>empty?</tt>, most notably Strings). Otherwise, +false+.
-
# Note that it always returns +true+ with boolean attributes.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# person = Task.new(title: '', is_done: false)
-
# person.attribute_present?(:title) # => false
-
# person.attribute_present?(:is_done) # => true
-
# person.name = 'Francesco'
-
# person.is_done = true
-
# person.attribute_present?(:title) # => true
-
# person.attribute_present?(:is_done) # => true
-
1
def attribute_present?(attribute)
-
value = read_attribute(attribute)
-
!value.nil? && !(value.respond_to?(:empty?) && value.empty?)
-
end
-
-
# Returns the column object for the named attribute. Returns +nil+ if the
-
# named attribute not exists.
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person.column_for_attribute(:name) # the result depends on the ConnectionAdapter
-
# # => #<ActiveRecord::ConnectionAdapters::SQLite3Column:0x007ff4ab083980 @name="name", @sql_type="varchar(255)", @null=true, ...>
-
#
-
# person.column_for_attribute(:nothing)
-
# # => nil
-
1
def column_for_attribute(name)
-
# FIXME: should this return a null object for columns that don't exist?
-
self.class.columns_hash[name.to_s]
-
end
-
-
# Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
-
# "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)). It raises
-
# <tt>ActiveModel::MissingAttributeError</tt> if the identified attribute is missing.
-
#
-
# Alias for the <tt>read_attribute</tt> method.
-
#
-
# class Person < ActiveRecord::Base
-
# belongs_to :organization
-
# end
-
#
-
# person = Person.new(name: 'Francesco', age: '22')
-
# person[:name] # => "Francesco"
-
# person[:age] # => 22
-
#
-
# person = Person.select('id').first
-
# person[:name] # => ActiveModel::MissingAttributeError: missing attribute: name
-
# person[:organization_id] # => ActiveModel::MissingAttributeError: missing attribute: organization_id
-
1
def [](attr_name)
-
read_attribute(attr_name) { |n| missing_attribute(n, caller) }
-
end
-
-
# Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
-
# (Alias for the protected <tt>write_attribute</tt> method).
-
#
-
# class Person < ActiveRecord::Base
-
# end
-
#
-
# person = Person.new
-
# person[:age] = '22'
-
# person[:age] # => 22
-
# person[:age] # => Fixnum
-
1
def []=(attr_name, value)
-
write_attribute(attr_name, value)
-
end
-
-
1
protected
-
-
1
def clone_attributes(reader_method = :read_attribute, attributes = {}) # :nodoc:
-
attribute_names.each do |name|
-
attributes[name] = clone_attribute_value(reader_method, name)
-
end
-
attributes
-
end
-
-
1
def clone_attribute_value(reader_method, attribute_name) # :nodoc:
-
value = send(reader_method, attribute_name)
-
value.duplicable? ? value.clone : value
-
rescue TypeError, NoMethodError
-
value
-
end
-
-
1
def arel_attributes_with_values_for_create(attribute_names) # :nodoc:
-
arel_attributes_with_values(attributes_for_create(attribute_names))
-
end
-
-
1
def arel_attributes_with_values_for_update(attribute_names) # :nodoc:
-
arel_attributes_with_values(attributes_for_update(attribute_names))
-
end
-
-
1
def attribute_method?(attr_name) # :nodoc:
-
defined?(@attributes) && @attributes.include?(attr_name)
-
end
-
-
1
private
-
-
# Returns a Hash of the Arel::Attributes and attribute values that have been
-
# type casted for use in an Arel insert/update method.
-
1
def arel_attributes_with_values(attribute_names)
-
attrs = {}
-
arel_table = self.class.arel_table
-
-
attribute_names.each do |name|
-
attrs[arel_table[name]] = typecasted_attribute_value(name)
-
end
-
attrs
-
end
-
-
# Filters the primary keys and readonly attributes from the attribute names.
-
1
def attributes_for_update(attribute_names)
-
attribute_names.select do |name|
-
column_for_attribute(name) && !pk_attribute?(name) && !readonly_attribute?(name)
-
end
-
end
-
-
# Filters out the primary keys, from the attribute names, when the primary
-
# key is to be generated (e.g. the id attribute has no value).
-
1
def attributes_for_create(attribute_names)
-
attribute_names.select do |name|
-
column_for_attribute(name) && !(pk_attribute?(name) && id.nil?)
-
end
-
end
-
-
1
def readonly_attribute?(name)
-
self.class.readonly_attributes.include?(name)
-
end
-
-
1
def pk_attribute?(name)
-
column_for_attribute(name).primary
-
end
-
-
1
def typecasted_attribute_value(name)
-
# FIXME: we need @attributes to be used consistently.
-
# If the values stored in @attributes were already typecasted, this code
-
# could be simplified
-
read_attribute(name)
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module AttributeMethods
-
# = Active Record Attribute Methods Before Type Cast
-
#
-
# <tt>ActiveRecord::AttributeMethods::BeforeTypeCast</tt> provides a way to
-
# read the value of the attributes before typecasting and deserialization.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# task = Task.new(id: '1', completed_on: '2012-10-21')
-
# task.id # => 1
-
# task.completed_on # => Sun, 21 Oct 2012
-
#
-
# task.attributes_before_type_cast
-
# # => {"id"=>"1", "completed_on"=>"2012-10-21", ... }
-
# task.read_attribute_before_type_cast('id') # => "1"
-
# task.read_attribute_before_type_cast('completed_on') # => "2012-10-21"
-
#
-
# In addition to #read_attribute_before_type_cast and #attributes_before_type_cast,
-
# it declares a method for all attributes with the <tt>*_before_type_cast</tt>
-
# suffix.
-
#
-
# task.id_before_type_cast # => "1"
-
# task.completed_on_before_type_cast # => "2012-10-21"
-
1
module BeforeTypeCast
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
attribute_method_suffix "_before_type_cast"
-
end
-
-
# Returns the value of the attribute identified by +attr_name+ before
-
# typecasting and deserialization.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# task = Task.new(id: '1', completed_on: '2012-10-21')
-
# task.read_attribute('id') # => 1
-
# task.read_attribute_before_type_cast('id') # => '1'
-
# task.read_attribute('completed_on') # => Sun, 21 Oct 2012
-
# task.read_attribute_before_type_cast('completed_on') # => "2012-10-21"
-
1
def read_attribute_before_type_cast(attr_name)
-
@attributes[attr_name]
-
end
-
-
# Returns a hash of attributes before typecasting and deserialization.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# task = Task.new(title: nil, is_done: true, completed_on: '2012-10-21')
-
# task.attributes
-
# # => {"id"=>nil, "title"=>nil, "is_done"=>true, "completed_on"=>Sun, 21 Oct 2012, "created_at"=>nil, "updated_at"=>nil}
-
# task.attributes_before_type_cast
-
# # => {"id"=>nil, "title"=>nil, "is_done"=>true, "completed_on"=>"2012-10-21", "created_at"=>nil, "updated_at"=>nil}
-
1
def attributes_before_type_cast
-
@attributes
-
end
-
-
1
private
-
-
# Handle *_before_type_cast for method_missing.
-
1
def attribute_before_type_cast(attribute_name)
-
read_attribute_before_type_cast(attribute_name)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/deprecation'
-
-
1
module ActiveRecord
-
1
module AttributeMethods
-
1
module Dirty # :nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
include ActiveModel::Dirty
-
-
1
included do
-
1
if self < ::ActiveRecord::Timestamp
-
raise "You cannot include Dirty after Timestamp"
-
end
-
-
1
class_attribute :partial_writes, instance_writer: false
-
1
self.partial_writes = true
-
-
1
def self.partial_updates=(v); self.partial_writes = v; end
-
1
def self.partial_updates?; partial_writes?; end
-
1
def self.partial_updates; partial_writes; end
-
-
1
ActiveSupport::Deprecation.deprecate_methods(
-
singleton_class,
-
:partial_updates= => :partial_writes=,
-
:partial_updates? => :partial_writes?,
-
:partial_updates => :partial_writes
-
)
-
end
-
-
# Attempts to +save+ the record and clears changed attributes if successful.
-
1
def save(*)
-
if status = super
-
@previously_changed = changes
-
@changed_attributes.clear
-
end
-
status
-
end
-
-
# Attempts to <tt>save!</tt> the record and clears changed attributes if successful.
-
1
def save!(*)
-
super.tap do
-
@previously_changed = changes
-
@changed_attributes.clear
-
end
-
end
-
-
# <tt>reload</tt> the record and clears changed attributes.
-
1
def reload(*)
-
super.tap do
-
@previously_changed.clear
-
@changed_attributes.clear
-
end
-
end
-
-
1
private
-
# Wrap write_attribute to remember original attribute value.
-
1
def write_attribute(attr, value)
-
attr = attr.to_s
-
-
# The attribute already has an unsaved change.
-
if attribute_changed?(attr)
-
old = @changed_attributes[attr]
-
@changed_attributes.delete(attr) unless _field_changed?(attr, old, value)
-
else
-
old = clone_attribute_value(:read_attribute, attr)
-
@changed_attributes[attr] = old if _field_changed?(attr, old, value)
-
end
-
-
# Carry on.
-
super(attr, value)
-
end
-
-
1
def update(*)
-
partial_writes? ? super(keys_for_partial_write) : super
-
end
-
-
1
def create(*)
-
partial_writes? ? super(keys_for_partial_write) : super
-
end
-
-
# Serialized attributes should always be written in case they've been
-
# changed in place.
-
1
def keys_for_partial_write
-
changed | (attributes.keys & self.class.serialized_attributes.keys)
-
end
-
-
1
def _field_changed?(attr, old, value)
-
if column = column_for_attribute(attr)
-
if column.number? && (changes_from_nil_to_empty_string?(column, old, value) ||
-
changes_from_zero_to_string?(old, value))
-
value = nil
-
else
-
value = column.type_cast(value)
-
end
-
end
-
-
old != value
-
end
-
-
1
def changes_from_nil_to_empty_string?(column, old, value)
-
# For nullable numeric columns, NULL gets stored in database for blank (i.e. '') values.
-
# Hence we don't record it as a change if the value changes from nil to ''.
-
# If an old value of 0 is set to '' we want this to get changed to nil as otherwise it'll
-
# be typecast back to 0 (''.to_i => 0)
-
column.null && (old.nil? || old == 0) && value.blank?
-
end
-
-
1
def changes_from_zero_to_string?(old, value)
-
# For columns with old 0 and value non-empty string
-
old == 0 && value.is_a?(String) && value.present? && value != '0'
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module AttributeMethods
-
1
module Query
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
attribute_method_suffix "?"
-
end
-
-
1
def query_attribute(attr_name)
-
value = read_attribute(attr_name) { |n| missing_attribute(n, caller) }
-
-
case value
-
when true then true
-
when false, nil then false
-
else
-
column = self.class.columns_hash[attr_name]
-
if column.nil?
-
if Numeric === value || value !~ /[^0-9]/
-
!value.to_i.zero?
-
else
-
return false if ActiveRecord::ConnectionAdapters::Column::FALSE_VALUES.include?(value)
-
!value.blank?
-
end
-
elsif column.number?
-
!value.zero?
-
else
-
!value.blank?
-
end
-
end
-
end
-
-
1
private
-
# Handle *? for method_missing.
-
1
def attribute?(attribute_name)
-
query_attribute(attribute_name)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module AttributeMethods
-
1
module Read
-
1
extend ActiveSupport::Concern
-
-
1
ATTRIBUTE_TYPES_CACHED_BY_DEFAULT = [:datetime, :timestamp, :time, :date]
-
-
1
included do
-
1
class_attribute :attribute_types_cached_by_default, instance_writer: false
-
1
self.attribute_types_cached_by_default = ATTRIBUTE_TYPES_CACHED_BY_DEFAULT
-
end
-
-
1
module ClassMethods
-
# +cache_attributes+ allows you to declare which converted attribute
-
# values should be cached. Usually caching only pays off for attributes
-
# with expensive conversion methods, like time related columns (e.g.
-
# +created_at+, +updated_at+).
-
1
def cache_attributes(*attribute_names)
-
cached_attributes.merge attribute_names.map { |attr| attr.to_s }
-
end
-
-
# Returns the attributes which are cached. By default time related columns
-
# with datatype <tt>:datetime, :timestamp, :time, :date</tt> are cached.
-
1
def cached_attributes
-
@cached_attributes ||= columns.select { |c| cacheable_column?(c) }.map { |col| col.name }.to_set
-
end
-
-
# Returns +true+ if the provided attribute is being cached.
-
1
def cache_attribute?(attr_name)
-
cached_attributes.include?(attr_name)
-
end
-
-
1
protected
-
-
# We want to generate the methods via module_eval rather than define_method,
-
# because define_method is slower on dispatch and uses more memory (because it
-
# creates a closure).
-
#
-
# But sometimes the database might return columns with characters that are not
-
# allowed in normal method names (like 'my_column(omg)'. So to work around this
-
# we first define with the __temp__ identifier, and then use alias method to
-
# rename it to what we want.
-
1
def define_method_attribute(attr_name)
-
generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
-
def __temp__
-
read_attribute('#{attr_name}') { |n| missing_attribute(n, caller) }
-
end
-
alias_method '#{attr_name}', :__temp__
-
undef_method :__temp__
-
STR
-
end
-
-
1
private
-
-
1
def cacheable_column?(column)
-
if attribute_types_cached_by_default == ATTRIBUTE_TYPES_CACHED_BY_DEFAULT
-
! serialized_attributes.include? column.name
-
else
-
attribute_types_cached_by_default.include?(column.type)
-
end
-
end
-
end
-
-
# Returns the value of the attribute identified by <tt>attr_name</tt> after
-
# it has been typecast (for example, "2004-12-12" in a data column is cast
-
# to a date object, like Date.new(2004, 12, 12)).
-
1
def read_attribute(attr_name)
-
# If it's cached, just return it
-
# We use #[] first as a perf optimization for non-nil values. See https://gist.github.com/3552829.
-
name = attr_name.to_s
-
@attributes_cache[name] || @attributes_cache.fetch(name) {
-
column = @columns_hash.fetch(name) {
-
return @attributes.fetch(name) {
-
if name == 'id' && self.class.primary_key != name
-
read_attribute(self.class.primary_key)
-
end
-
}
-
}
-
-
value = @attributes.fetch(name) {
-
return block_given? ? yield(name) : nil
-
}
-
-
if self.class.cache_attribute?(name)
-
@attributes_cache[name] = column.type_cast(value)
-
else
-
column.type_cast value
-
end
-
}
-
end
-
-
1
private
-
-
1
def attribute(attribute_name)
-
read_attribute(attribute_name)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module AttributeMethods
-
1
module Serialization
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
# Returns a hash of all the attributes that have been specified for
-
# serialization as keys and their class restriction as values.
-
1
class_attribute :serialized_attributes, instance_accessor: false
-
1
self.serialized_attributes = {}
-
end
-
-
1
module ClassMethods
-
# If you have an attribute that needs to be saved to the database as an
-
# object, and retrieved as the same object, then specify the name of that
-
# attribute using this method and it will be handled automatically. The
-
# serialization is done through YAML. If +class_name+ is specified, the
-
# serialized object must be of that class on retrieval or
-
# <tt>SerializationTypeMismatch</tt> will be raised.
-
#
-
# ==== Parameters
-
#
-
# * +attr_name+ - The field name that should be serialized.
-
# * +class_name+ - Optional, class name that the object type should be equal to.
-
#
-
# ==== Example
-
#
-
# # Serialize a preferences attribute.
-
# class User < ActiveRecord::Base
-
# serialize :preferences
-
# end
-
1
def serialize(attr_name, class_name = Object)
-
include Behavior
-
-
coder = if [:load, :dump].all? { |x| class_name.respond_to?(x) }
-
class_name
-
else
-
Coders::YAMLColumn.new(class_name)
-
end
-
-
# merge new serialized attribute and create new hash to ensure that each class in inheritance hierarchy
-
# has its own hash of own serialized attributes
-
self.serialized_attributes = serialized_attributes.merge(attr_name.to_s => coder)
-
end
-
end
-
-
1
def serialized_attributes
-
message = "Instance level serialized_attributes method is deprecated, please use class level method."
-
ActiveSupport::Deprecation.warn message
-
defined?(@serialized_attributes) ? @serialized_attributes : self.class.serialized_attributes
-
end
-
-
1
class Type # :nodoc:
-
1
def initialize(column)
-
@column = column
-
end
-
-
1
def type_cast(value)
-
value.unserialized_value
-
end
-
-
1
def type
-
@column.type
-
end
-
end
-
-
1
class Attribute < Struct.new(:coder, :value, :state) # :nodoc:
-
1
def unserialized_value
-
state == :serialized ? unserialize : value
-
end
-
-
1
def serialized_value
-
state == :unserialized ? serialize : value
-
end
-
-
1
def unserialize
-
self.state = :unserialized
-
self.value = coder.load(value)
-
end
-
-
1
def serialize
-
self.state = :serialized
-
self.value = coder.dump(value)
-
end
-
end
-
-
# This is only added to the model when serialize is called, which
-
# ensures we do not make things slower when serialization is not used.
-
1
module Behavior #:nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
1
def initialize_attributes(attributes, options = {})
-
serialized = (options.delete(:serialized) { true }) ? :serialized : :unserialized
-
super(attributes, options)
-
-
serialized_attributes.each do |key, coder|
-
if attributes.key?(key)
-
attributes[key] = Attribute.new(coder, attributes[key], serialized)
-
end
-
end
-
-
attributes
-
end
-
end
-
-
1
def type_cast_attribute_for_write(column, value)
-
if column && coder = self.class.serialized_attributes[column.name]
-
Attribute.new(coder, value, :unserialized)
-
else
-
super
-
end
-
end
-
-
1
def read_attribute_before_type_cast(attr_name)
-
if self.class.serialized_attributes.include?(attr_name)
-
super.unserialized_value
-
else
-
super
-
end
-
end
-
-
1
def attributes_before_type_cast
-
super.dup.tap do |attributes|
-
self.class.serialized_attributes.each_key do |key|
-
if attributes.key?(key)
-
attributes[key] = attributes[key].unserialized_value
-
end
-
end
-
end
-
end
-
-
1
def typecasted_attribute_value(name)
-
if self.class.serialized_attributes.include?(name)
-
@attributes[name].serialized_value
-
else
-
super
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module AttributeMethods
-
1
module TimeZoneConversion
-
1
class Type # :nodoc:
-
1
def initialize(column)
-
@column = column
-
end
-
-
1
def type_cast(value)
-
value = @column.type_cast(value)
-
value.acts_like?(:time) ? value.in_time_zone : value
-
end
-
-
1
def type
-
@column.type
-
end
-
end
-
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
mattr_accessor :time_zone_aware_attributes, instance_writer: false
-
1
self.time_zone_aware_attributes = false
-
-
1
class_attribute :skip_time_zone_conversion_for_attributes, instance_writer: false
-
1
self.skip_time_zone_conversion_for_attributes = []
-
end
-
-
1
module ClassMethods
-
1
protected
-
# Defined for all +datetime+ and +timestamp+ attributes when +time_zone_aware_attributes+ are enabled.
-
# This enhanced write method will automatically convert the time passed to it to the zone stored in Time.zone.
-
1
def define_method_attribute=(attr_name)
-
if create_time_zone_conversion_attribute?(attr_name, columns_hash[attr_name])
-
method_body, line = <<-EOV, __LINE__ + 1
-
def #{attr_name}=(original_time)
-
time = original_time
-
unless time.acts_like?(:time)
-
time = time.is_a?(String) ? Time.zone.parse(time) : time.to_time rescue time
-
end
-
zoned_time = time && time.in_time_zone rescue nil
-
rounded_time = round_usec(zoned_time)
-
rounded_value = round_usec(read_attribute("#{attr_name}"))
-
if (rounded_value != rounded_time) || (!rounded_value && original_time)
-
write_attribute("#{attr_name}", original_time)
-
#{attr_name}_will_change!
-
@attributes_cache["#{attr_name}"] = zoned_time
-
end
-
end
-
EOV
-
generated_attribute_methods.module_eval(method_body, __FILE__, line)
-
else
-
super
-
end
-
end
-
-
1
private
-
1
def create_time_zone_conversion_attribute?(name, column)
-
time_zone_aware_attributes &&
-
!self.skip_time_zone_conversion_for_attributes.include?(name.to_sym) &&
-
[:datetime, :timestamp].include?(column.type)
-
end
-
end
-
-
1
private
-
1
def round_usec(value)
-
return unless value
-
value.change(:usec => 0)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module AttributeMethods
-
1
module Write
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
attribute_method_suffix "="
-
end
-
-
1
module ClassMethods
-
1
protected
-
1
def define_method_attribute=(attr_name)
-
if attr_name =~ ActiveModel::AttributeMethods::NAME_COMPILABLE_REGEXP
-
generated_attribute_methods.module_eval("def #{attr_name}=(new_value); write_attribute('#{attr_name}', new_value); end", __FILE__, __LINE__)
-
else
-
generated_attribute_methods.send(:define_method, "#{attr_name}=") do |new_value|
-
write_attribute(attr_name, new_value)
-
end
-
end
-
end
-
end
-
-
# Updates the attribute identified by <tt>attr_name</tt> with the
-
# specified +value+. Empty strings for fixnum and float columns are
-
# turned into +nil+.
-
1
def write_attribute(attr_name, value)
-
attr_name = attr_name.to_s
-
attr_name = self.class.primary_key if attr_name == 'id' && self.class.primary_key
-
@attributes_cache.delete(attr_name)
-
column = column_for_attribute(attr_name)
-
-
# If we're dealing with a binary column, write the data to the cache
-
# so we don't attempt to typecast multiple times.
-
if column && column.binary?
-
@attributes_cache[attr_name] = value
-
end
-
-
if column || @attributes.has_key?(attr_name)
-
@attributes[attr_name] = type_cast_attribute_for_write(column, value)
-
else
-
raise ActiveModel::MissingAttributeError, "can't write unknown attribute `#{attr_name}'"
-
end
-
end
-
1
alias_method :raw_write_attribute, :write_attribute
-
-
1
private
-
# Handle *= for method_missing.
-
1
def attribute=(attribute_name, value)
-
write_attribute(attribute_name, value)
-
end
-
-
1
def type_cast_attribute_for_write(column, value)
-
return value unless column
-
-
column.type_cast_for_write value
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record Autosave Association
-
#
-
# +AutosaveAssociation+ is a module that takes care of automatically saving
-
# associated records when their parent is saved. In addition to saving, it
-
# also destroys any associated records that were marked for destruction.
-
# (See +mark_for_destruction+ and <tt>marked_for_destruction?</tt>).
-
#
-
# Saving of the parent, its associations, and the destruction of marked
-
# associations, all happen inside a transaction. This should never leave the
-
# database in an inconsistent state.
-
#
-
# If validations for any of the associations fail, their error messages will
-
# be applied to the parent.
-
#
-
# Note that it also means that associations marked for destruction won't
-
# be destroyed directly. They will however still be marked for destruction.
-
#
-
# Note that <tt>:autosave => false</tt> is not same as not declaring <tt>:autosave</tt>.
-
# When the <tt>:autosave</tt> option is not present new associations are saved.
-
#
-
# == Validation
-
#
-
# Children records are validated unless <tt>:validate</tt> is +false+.
-
#
-
# == Callbacks
-
#
-
# Association with autosave option defines several callbacks on your
-
# model (before_save, after_create, after_update). Please note that
-
# callbacks are executed in the order they were defined in
-
# model. You should avoid modifying the association content, before
-
# autosave callbacks are executed. Placing your callbacks after
-
# associations is usually a good practice.
-
#
-
# == Examples
-
#
-
# === One-to-one Example
-
#
-
# class Post
-
# has_one :author, :autosave => true
-
# end
-
#
-
# Saving changes to the parent and its associated model can now be performed
-
# automatically _and_ atomically:
-
#
-
# post = Post.find(1)
-
# post.title # => "The current global position of migrating ducks"
-
# post.author.name # => "alloy"
-
#
-
# post.title = "On the migration of ducks"
-
# post.author.name = "Eloy Duran"
-
#
-
# post.save
-
# post.reload
-
# post.title # => "On the migration of ducks"
-
# post.author.name # => "Eloy Duran"
-
#
-
# Destroying an associated model, as part of the parent's save action, is as
-
# simple as marking it for destruction:
-
#
-
# post.author.mark_for_destruction
-
# post.author.marked_for_destruction? # => true
-
#
-
# Note that the model is _not_ yet removed from the database:
-
#
-
# id = post.author.id
-
# Author.find_by_id(id).nil? # => false
-
#
-
# post.save
-
# post.reload.author # => nil
-
#
-
# Now it _is_ removed from the database:
-
#
-
# Author.find_by_id(id).nil? # => true
-
#
-
# === One-to-many Example
-
#
-
# When <tt>:autosave</tt> is not declared new children are saved when their parent is saved:
-
#
-
# class Post
-
# has_many :comments # :autosave option is not declared
-
# end
-
#
-
# post = Post.new(:title => 'ruby rocks')
-
# post.comments.build(:body => 'hello world')
-
# post.save # => saves both post and comment
-
#
-
# post = Post.create(:title => 'ruby rocks')
-
# post.comments.build(:body => 'hello world')
-
# post.save # => saves both post and comment
-
#
-
# post = Post.create(:title => 'ruby rocks')
-
# post.comments.create(:body => 'hello world')
-
# post.save # => saves both post and comment
-
#
-
# When <tt>:autosave</tt> is true all children are saved, no matter whether they
-
# are new records or not:
-
#
-
# class Post
-
# has_many :comments, :autosave => true
-
# end
-
#
-
# post = Post.create(:title => 'ruby rocks')
-
# post.comments.create(:body => 'hello world')
-
# post.comments[0].body = 'hi everyone'
-
# post.save # => saves both post and comment, with 'hi everyone' as body
-
#
-
# Destroying one of the associated models as part of the parent's save action
-
# is as simple as marking it for destruction:
-
#
-
# post.comments.last.mark_for_destruction
-
# post.comments.last.marked_for_destruction? # => true
-
# post.comments.length # => 2
-
#
-
# Note that the model is _not_ yet removed from the database:
-
#
-
# id = post.comments.last.id
-
# Comment.find_by_id(id).nil? # => false
-
#
-
# post.save
-
# post.reload.comments.length # => 1
-
#
-
# Now it _is_ removed from the database:
-
#
-
# Comment.find_by_id(id).nil? # => true
-
-
1
module AutosaveAssociation
-
1
extend ActiveSupport::Concern
-
-
1
module AssociationBuilderExtension #:nodoc:
-
1
def build
-
model.send(:add_autosave_association_callbacks, reflection)
-
super
-
end
-
end
-
-
1
included do
-
1
Associations::Builder::Association.class_eval do
-
1
self.valid_options << :autosave
-
1
include AssociationBuilderExtension
-
end
-
end
-
-
1
module ClassMethods
-
1
private
-
-
1
def define_non_cyclic_method(name, reflection, &block)
-
define_method(name) do |*args|
-
result = true; @_already_called ||= {}
-
# Loop prevention for validation of associations
-
unless @_already_called[[name, reflection.name]]
-
begin
-
@_already_called[[name, reflection.name]]=true
-
result = instance_eval(&block)
-
ensure
-
@_already_called[[name, reflection.name]]=false
-
end
-
end
-
-
result
-
end
-
end
-
-
# Adds validation and save callbacks for the association as specified by
-
# the +reflection+.
-
#
-
# For performance reasons, we don't check whether to validate at runtime.
-
# However the validation and callback methods are lazy and those methods
-
# get created when they are invoked for the very first time. However,
-
# this can change, for instance, when using nested attributes, which is
-
# called _after_ the association has been defined. Since we don't want
-
# the callbacks to get defined multiple times, there are guards that
-
# check if the save or validation methods have already been defined
-
# before actually defining them.
-
1
def add_autosave_association_callbacks(reflection)
-
save_method = :"autosave_associated_records_for_#{reflection.name}"
-
validation_method = :"validate_associated_records_for_#{reflection.name}"
-
collection = reflection.collection?
-
-
unless method_defined?(save_method)
-
if collection
-
before_save :before_save_collection_association
-
-
define_non_cyclic_method(save_method, reflection) { save_collection_association(reflection) }
-
# Doesn't use after_save as that would save associations added in after_create/after_update twice
-
after_create save_method
-
after_update save_method
-
elsif reflection.macro == :has_one
-
define_method(save_method) { save_has_one_association(reflection) }
-
# Configures two callbacks instead of a single after_save so that
-
# the model may rely on their execution order relative to its
-
# own callbacks.
-
#
-
# For example, given that after_creates run before after_saves, if
-
# we configured instead an after_save there would be no way to fire
-
# a custom after_create callback after the child association gets
-
# created.
-
after_create save_method
-
after_update save_method
-
else
-
define_non_cyclic_method(save_method, reflection) { save_belongs_to_association(reflection) }
-
before_save save_method
-
end
-
end
-
-
if reflection.validate? && !method_defined?(validation_method)
-
method = (collection ? :validate_collection_association : :validate_single_association)
-
define_non_cyclic_method(validation_method, reflection) { send(method, reflection) }
-
validate validation_method
-
end
-
end
-
end
-
-
# Reloads the attributes of the object as usual and clears <tt>marked_for_destruction</tt> flag.
-
1
def reload(options = nil)
-
@marked_for_destruction = false
-
super
-
end
-
-
# Marks this record to be destroyed as part of the parents save transaction.
-
# This does _not_ actually destroy the record instantly, rather child record will be destroyed
-
# when <tt>parent.save</tt> is called.
-
#
-
# Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model.
-
1
def mark_for_destruction
-
@marked_for_destruction = true
-
end
-
-
# Returns whether or not this record will be destroyed as part of the parents save transaction.
-
#
-
# Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model.
-
1
def marked_for_destruction?
-
@marked_for_destruction
-
end
-
-
# Returns whether or not this record has been changed in any way (including whether
-
# any of its nested autosave associations are likewise changed)
-
1
def changed_for_autosave?
-
new_record? || changed? || marked_for_destruction? || nested_records_changed_for_autosave?
-
end
-
-
1
private
-
-
# Returns the record for an association collection that should be validated
-
# or saved. If +autosave+ is +false+ only new records will be returned,
-
# unless the parent is/was a new record itself.
-
1
def associated_records_to_validate_or_save(association, new_record, autosave)
-
if new_record
-
association && association.target
-
elsif autosave
-
association.target.find_all { |record| record.changed_for_autosave? }
-
else
-
association.target.find_all { |record| record.new_record? }
-
end
-
end
-
-
# go through nested autosave associations that are loaded in memory (without loading
-
# any new ones), and return true if is changed for autosave
-
1
def nested_records_changed_for_autosave?
-
self.class.reflect_on_all_autosave_associations.any? do |reflection|
-
association = association_instance_get(reflection.name)
-
association && Array.wrap(association.target).any? { |a| a.changed_for_autosave? }
-
end
-
end
-
-
# Validate the association if <tt>:validate</tt> or <tt>:autosave</tt> is
-
# turned on for the association.
-
1
def validate_single_association(reflection)
-
association = association_instance_get(reflection.name)
-
record = association && association.reader
-
association_valid?(reflection, record) if record
-
end
-
-
# Validate the associated records if <tt>:validate</tt> or
-
# <tt>:autosave</tt> is turned on for the association specified by
-
# +reflection+.
-
1
def validate_collection_association(reflection)
-
if association = association_instance_get(reflection.name)
-
if records = associated_records_to_validate_or_save(association, new_record?, reflection.options[:autosave])
-
records.each { |record| association_valid?(reflection, record) }
-
end
-
end
-
end
-
-
# Returns whether or not the association is valid and applies any errors to
-
# the parent, <tt>self</tt>, if it wasn't. Skips any <tt>:autosave</tt>
-
# enabled records if they're marked_for_destruction? or destroyed.
-
1
def association_valid?(reflection, record)
-
return true if record.destroyed? || record.marked_for_destruction?
-
-
unless valid = record.valid?(validation_context)
-
if reflection.options[:autosave]
-
record.errors.each do |attribute, message|
-
attribute = "#{reflection.name}.#{attribute}"
-
errors[attribute] << message
-
errors[attribute].uniq!
-
end
-
else
-
errors.add(reflection.name)
-
end
-
end
-
valid
-
end
-
-
# Is used as a before_save callback to check while saving a collection
-
# association whether or not the parent was a new record before saving.
-
1
def before_save_collection_association
-
@new_record_before_save = new_record?
-
true
-
end
-
-
# Saves any new associated records, or all loaded autosave associations if
-
# <tt>:autosave</tt> is enabled on the association.
-
#
-
# In addition, it destroys all children that were marked for destruction
-
# with mark_for_destruction.
-
#
-
# This all happens inside a transaction, _if_ the Transactions module is included into
-
# ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
-
1
def save_collection_association(reflection)
-
if association = association_instance_get(reflection.name)
-
autosave = reflection.options[:autosave]
-
-
if records = associated_records_to_validate_or_save(association, @new_record_before_save, autosave)
-
records_to_destroy = []
-
records.each do |record|
-
next if record.destroyed?
-
-
saved = true
-
-
if autosave && record.marked_for_destruction?
-
records_to_destroy << record
-
elsif autosave != false && (@new_record_before_save || record.new_record?)
-
if autosave
-
saved = association.insert_record(record, false)
-
else
-
association.insert_record(record) unless reflection.nested?
-
end
-
elsif autosave
-
saved = record.save(:validate => false)
-
end
-
-
raise ActiveRecord::Rollback unless saved
-
end
-
-
records_to_destroy.each do |record|
-
association.destroy(record)
-
end
-
end
-
-
# reconstruct the scope now that we know the owner's id
-
association.send(:reset_scope) if association.respond_to?(:reset_scope)
-
end
-
end
-
-
# Saves the associated record if it's new or <tt>:autosave</tt> is enabled
-
# on the association.
-
#
-
# In addition, it will destroy the association if it was marked for
-
# destruction with mark_for_destruction.
-
#
-
# This all happens inside a transaction, _if_ the Transactions module is included into
-
# ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
-
1
def save_has_one_association(reflection)
-
association = association_instance_get(reflection.name)
-
record = association && association.load_target
-
if record && !record.destroyed?
-
autosave = reflection.options[:autosave]
-
-
if autosave && record.marked_for_destruction?
-
record.destroy
-
else
-
key = reflection.options[:primary_key] ? send(reflection.options[:primary_key]) : id
-
if autosave != false && (new_record? || record.new_record? || record[reflection.foreign_key] != key || autosave)
-
unless reflection.through_reflection
-
record[reflection.foreign_key] = key
-
end
-
-
saved = record.save(:validate => !autosave)
-
raise ActiveRecord::Rollback if !saved && autosave
-
saved
-
end
-
end
-
end
-
end
-
-
# Saves the associated record if it's new or <tt>:autosave</tt> is enabled.
-
#
-
# In addition, it will destroy the association if it was marked for destruction.
-
1
def save_belongs_to_association(reflection)
-
association = association_instance_get(reflection.name)
-
record = association && association.load_target
-
if record && !record.destroyed?
-
autosave = reflection.options[:autosave]
-
-
if autosave && record.marked_for_destruction?
-
self[reflection.foreign_key] = nil
-
record.destroy
-
elsif autosave != false
-
saved = record.save(:validate => !autosave) if record.new_record? || (autosave && record.changed_for_autosave?)
-
-
if association.updated?
-
association_id = record.send(reflection.options[:primary_key] || :id)
-
self[reflection.foreign_key] = association_id
-
association.loaded!
-
end
-
-
saved if autosave
-
end
-
end
-
end
-
end
-
end
-
1
require 'yaml'
-
1
require 'set'
-
1
require 'active_support/benchmarkable'
-
1
require 'active_support/dependencies'
-
1
require 'active_support/descendants_tracker'
-
1
require 'active_support/time'
-
1
require 'active_support/core_ext/class/attribute_accessors'
-
1
require 'active_support/core_ext/class/delegating_attributes'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/hash/deep_merge'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/core_ext/string/behavior'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'active_support/core_ext/module/introspection'
-
1
require 'active_support/core_ext/object/duplicable'
-
1
require 'arel'
-
1
require 'active_record/errors'
-
1
require 'active_record/log_subscriber'
-
1
require 'active_record/explain_subscriber'
-
-
1
module ActiveRecord #:nodoc:
-
# = Active Record
-
#
-
# Active Record objects don't specify their attributes directly, but rather infer them from
-
# the table definition with which they're linked. Adding, removing, and changing attributes
-
# and their type is done directly in the database. Any change is instantly reflected in the
-
# Active Record objects. The mapping that binds a given Active Record class to a certain
-
# database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
-
#
-
# See the mapping rules in table_name and the full example in link:files/activerecord/README_rdoc.html for more insight.
-
#
-
# == Creation
-
#
-
# Active Records accept constructor parameters either in a hash or as a block. The hash
-
# method is especially useful when you're receiving the data from somewhere else, like an
-
# HTTP request. It works like this:
-
#
-
# user = User.new(:name => "David", :occupation => "Code Artist")
-
# user.name # => "David"
-
#
-
# You can also use block initialization:
-
#
-
# user = User.new do |u|
-
# u.name = "David"
-
# u.occupation = "Code Artist"
-
# end
-
#
-
# And of course you can just create a bare object and specify the attributes after the fact:
-
#
-
# user = User.new
-
# user.name = "David"
-
# user.occupation = "Code Artist"
-
#
-
# == Conditions
-
#
-
# Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement.
-
# The array form is to be used when the condition input is tainted and requires sanitization. The string form can
-
# be used for statements that don't involve tainted data. The hash form works much like the array form, except
-
# only equality and range is possible. Examples:
-
#
-
# class User < ActiveRecord::Base
-
# def self.authenticate_unsafely(user_name, password)
-
# where("user_name = '#{user_name}' AND password = '#{password}'").first
-
# end
-
#
-
# def self.authenticate_safely(user_name, password)
-
# where("user_name = ? AND password = ?", user_name, password).first
-
# end
-
#
-
# def self.authenticate_safely_simply(user_name, password)
-
# where(:user_name => user_name, :password => password).first
-
# end
-
# end
-
#
-
# The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query
-
# and is thus susceptible to SQL-injection attacks if the <tt>user_name</tt> and +password+
-
# parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and
-
# <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+
-
# before inserting them in the query, which will ensure that an attacker can't escape the
-
# query and fake the login (or worse).
-
#
-
# When using multiple parameters in the conditions, it can easily become hard to read exactly
-
# what the fourth or fifth question mark is supposed to represent. In those cases, you can
-
# resort to named bind variables instead. That's done by replacing the question marks with
-
# symbols and supplying a hash with values for the matching symbol keys:
-
#
-
# Company.where(
-
# "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
-
# { :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' }
-
# ).first
-
#
-
# Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
-
# operator. For instance:
-
#
-
# Student.where(:first_name => "Harvey", :status => 1)
-
# Student.where(params[:student])
-
#
-
# A range may be used in the hash to use the SQL BETWEEN operator:
-
#
-
# Student.where(:grade => 9..12)
-
#
-
# An array may be used in the hash to use the SQL IN operator:
-
#
-
# Student.where(:grade => [9,11,12])
-
#
-
# When joining tables, nested hashes or keys written in the form 'table_name.column_name'
-
# can be used to qualify the table name of a particular condition. For instance:
-
#
-
# Student.joins(:schools).where(:schools => { :category => 'public' })
-
# Student.joins(:schools).where('schools.category' => 'public' )
-
#
-
# == Overwriting default accessors
-
#
-
# All column values are automatically available through basic accessors on the Active Record
-
# object, but sometimes you want to specialize this behavior. This can be done by overwriting
-
# the default accessors (using the same name as the attribute) and calling
-
# <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually
-
# change things.
-
#
-
# class Song < ActiveRecord::Base
-
# # Uses an integer of seconds to hold the length of the song
-
#
-
# def length=(minutes)
-
# write_attribute(:length, minutes.to_i * 60)
-
# end
-
#
-
# def length
-
# read_attribute(:length) / 60
-
# end
-
# end
-
#
-
# You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt>
-
# instead of <tt>write_attribute(:attribute, value)</tt> and <tt>read_attribute(:attribute)</tt>.
-
#
-
# == Attribute query methods
-
#
-
# In addition to the basic accessors, query methods are also automatically available on the Active Record object.
-
# Query methods allow you to test whether an attribute value is present.
-
#
-
# For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call
-
# to determine whether the user has a name:
-
#
-
# user = User.new(:name => "David")
-
# user.name? # => true
-
#
-
# anonymous = User.new(:name => "")
-
# anonymous.name? # => false
-
#
-
# == Accessing attributes before they have been typecasted
-
#
-
# Sometimes you want to be able to read the raw attribute data without having the column-determined
-
# typecast run its course first. That can be done by using the <tt><attribute>_before_type_cast</tt>
-
# accessors that all attributes have. For example, if your Account model has a <tt>balance</tt> attribute,
-
# you can call <tt>account.balance_before_type_cast</tt> or <tt>account.id_before_type_cast</tt>.
-
#
-
# This is especially useful in validation situations where the user might supply a string for an
-
# integer field and you want to display the original string back in an error message. Accessing the
-
# attribute normally would typecast the string to 0, which isn't what you want.
-
#
-
# == Dynamic attribute-based finders
-
#
-
# Dynamic attribute-based finders are a cleaner way of getting (and/or creating) objects
-
# by simple queries without turning to SQL. They work by appending the name of an attribute
-
# to <tt>find_by_</tt>, <tt>find_last_by_</tt>, or <tt>find_all_by_</tt> and thus produces finders
-
# like <tt>Person.find_by_user_name</tt>, <tt>Person.find_all_by_last_name</tt>, and
-
# <tt>Payment.find_by_transaction_id</tt>. Instead of writing
-
# <tt>Person.where(:user_name => user_name).first</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>.
-
# And instead of writing <tt>Person.where(:last_name => last_name).all</tt>, you just do
-
# <tt>Person.find_all_by_last_name(last_name)</tt>.
-
#
-
# It's possible to add an exclamation point (!) on the end of the dynamic finders to get them to raise an
-
# <tt>ActiveRecord::RecordNotFound</tt> error if they do not return any records,
-
# like <tt>Person.find_by_last_name!</tt>.
-
#
-
# It's also possible to use multiple attributes in the same find by separating them with "_and_".
-
#
-
# Person.where(:user_name => user_name, :password => password).first
-
# Person.find_by_user_name_and_password(user_name, password) # with dynamic finder
-
#
-
# It's even possible to call these dynamic finder methods on relations and named scopes.
-
#
-
# Payment.order("created_on").find_all_by_amount(50)
-
# Payment.pending.find_last_by_amount(100)
-
#
-
# The same dynamic finder style can be used to create the object if it doesn't already exist.
-
# This dynamic finder is called with <tt>find_or_create_by_</tt> and will return the object if
-
# it already exists and otherwise creates it, then returns it. Protected attributes won't be set
-
# unless they are given in a block.
-
#
-
# # No 'Summer' tag exists
-
# Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
-
#
-
# # Now the 'Summer' tag does exist
-
# Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
-
#
-
# # Now 'Bob' exist and is an 'admin'
-
# User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true }
-
#
-
# Adding an exclamation point (!) on to the end of <tt>find_or_create_by_</tt> will
-
# raise an <tt>ActiveRecord::RecordInvalid</tt> error if the new record is invalid.
-
#
-
# Use the <tt>find_or_initialize_by_</tt> finder if you want to return a new record without
-
# saving it first. Protected attributes won't be set unless they are given in a block.
-
#
-
# # No 'Winter' tag exists
-
# winter = Tag.find_or_initialize_by_name("Winter")
-
# winter.persisted? # false
-
#
-
# To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of
-
# a list of parameters.
-
#
-
# Tag.find_or_create_by_name(:name => "rails", :creator => current_user)
-
#
-
# That will either find an existing tag named "rails", or create a new one while setting the
-
# user that created it.
-
#
-
# Just like <tt>find_by_*</tt>, you can also use <tt>scoped_by_*</tt> to retrieve data. The good thing about
-
# using this feature is that the very first time result is returned using <tt>method_missing</tt> technique
-
# but after that the method is declared on the class. Henceforth <tt>method_missing</tt> will not be hit.
-
#
-
# User.scoped_by_user_name('David')
-
#
-
# == Saving arrays, hashes, and other non-mappable objects in text columns
-
#
-
# Active Record can serialize any object in text columns using YAML. To do so, you must
-
# specify this with a call to the class method +serialize+.
-
# This makes it possible to store arrays, hashes, and other non-mappable objects without doing
-
# any additional work.
-
#
-
# class User < ActiveRecord::Base
-
# serialize :preferences
-
# end
-
#
-
# user = User.create(:preferences => { "background" => "black", "display" => large })
-
# User.find(user.id).preferences # => { "background" => "black", "display" => large }
-
#
-
# You can also specify a class option as the second parameter that'll raise an exception
-
# if a serialized object is retrieved as a descendant of a class not in the hierarchy.
-
#
-
# class User < ActiveRecord::Base
-
# serialize :preferences, Hash
-
# end
-
#
-
# user = User.create(:preferences => %w( one two three ))
-
# User.find(user.id).preferences # raises SerializationTypeMismatch
-
#
-
# When you specify a class option, the default value for that attribute will be a new
-
# instance of that class.
-
#
-
# class User < ActiveRecord::Base
-
# serialize :preferences, OpenStruct
-
# end
-
#
-
# user = User.new
-
# user.preferences.theme_color = "red"
-
#
-
#
-
# == Single table inheritance
-
#
-
# Active Record allows inheritance by storing the name of the class in a column that by
-
# default is named "type" (can be changed by overwriting <tt>Base.inheritance_column</tt>).
-
# This means that an inheritance looking like this:
-
#
-
# class Company < ActiveRecord::Base; end
-
# class Firm < Company; end
-
# class Client < Company; end
-
# class PriorityClient < Client; end
-
#
-
# When you do <tt>Firm.create(:name => "37signals")</tt>, this record will be saved in
-
# the companies table with type = "Firm". You can then fetch this row again using
-
# <tt>Company.where(:name => '37signals').first</tt> and it will return a Firm object.
-
#
-
# If you don't have a type column defined in your table, single-table inheritance won't
-
# be triggered. In that case, it'll work just like normal subclasses with no special magic
-
# for differentiating between them or reloading the right type with find.
-
#
-
# Note, all the attributes for all the cases are kept in the same table. Read more:
-
# http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
-
#
-
# == Connection to multiple databases in different models
-
#
-
# Connections are usually created through ActiveRecord::Base.establish_connection and retrieved
-
# by ActiveRecord::Base.connection. All classes inheriting from ActiveRecord::Base will use this
-
# connection. But you can also set a class-specific connection. For example, if Course is an
-
# ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
-
# and Course and all of its subclasses will use this connection instead.
-
#
-
# This feature is implemented by keeping a connection pool in ActiveRecord::Base that is
-
# a Hash indexed by the class. If a connection is requested, the retrieve_connection method
-
# will go up the class-hierarchy until a connection is found in the connection pool.
-
#
-
# == Exceptions
-
#
-
# * ActiveRecordError - Generic error class and superclass of all other errors raised by Active Record.
-
# * AdapterNotSpecified - The configuration hash used in <tt>establish_connection</tt> didn't include an
-
# <tt>:adapter</tt> key.
-
# * AdapterNotFound - The <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a
-
# non-existent adapter
-
# (or a bad spelling of an existing one).
-
# * AssociationTypeMismatch - The object assigned to the association wasn't of the type
-
# specified in the association definition.
-
# * AttributeAssignmentError - An error occurred while doing a mass assignment through the
-
# <tt>attributes=</tt> method.
-
# You can inspect the +attribute+ property of the exception object to determine which attribute
-
# triggered the error.
-
# * ConnectionNotEstablished - No connection has been established. Use <tt>establish_connection</tt>
-
# before querying.
-
# * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the
-
# <tt>attributes=</tt> method. The +errors+ property of this exception contains an array of
-
# AttributeAssignmentError
-
# objects that should be inspected to determine which attributes triggered the errors.
-
# * RecordInvalid - raised by save! and create! when the record is invalid.
-
# * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist
-
# or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal
-
# nothing was found, please check its documentation for further details.
-
# * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
-
# * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
-
#
-
# *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
-
# So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all
-
# instances in the current object space.
-
1
class Base
-
1
extend ActiveModel::Observing::ClassMethods
-
1
extend ActiveModel::Naming
-
-
1
extend ActiveSupport::Benchmarkable
-
1
extend ActiveSupport::DescendantsTracker
-
-
1
extend ConnectionHandling
-
1
extend QueryCache::ClassMethods
-
1
extend Querying
-
1
extend Translation
-
1
extend DynamicMatchers
-
1
extend Explain
-
-
1
include Persistence
-
1
include ReadonlyAttributes
-
1
include ModelSchema
-
1
include Inheritance
-
1
include Scoping
-
1
include Sanitization
-
1
include AttributeAssignment
-
1
include ActiveModel::Conversion
-
1
include Integration
-
1
include Validations
-
1
include CounterCache
-
1
include Locking::Optimistic
-
1
include Locking::Pessimistic
-
1
include AttributeMethods
-
1
include Callbacks
-
1
include ActiveModel::Observing
-
1
include Timestamp
-
1
include Associations
-
1
include ActiveModel::SecurePassword
-
1
include AutosaveAssociation
-
1
include NestedAttributes
-
1
include Aggregations
-
1
include Transactions
-
1
include Reflection
-
1
include Serialization
-
1
include Store
-
1
include Core
-
end
-
-
1
ActiveSupport.run_load_hooks(:active_record, Base)
-
end
-
1
module ActiveRecord
-
# = Active Record Callbacks
-
#
-
# Callbacks are hooks into the life cycle of an Active Record object that allow you to trigger logic
-
# before or after an alteration of the object state. This can be used to make sure that associated and
-
# dependent objects are deleted when +destroy+ is called (by overwriting +before_destroy+) or to massage attributes
-
# before they're validated (by overwriting +before_validation+). As an example of the callbacks initiated, consider
-
# the <tt>Base#save</tt> call for a new record:
-
#
-
# * (-) <tt>save</tt>
-
# * (-) <tt>valid</tt>
-
# * (1) <tt>before_validation</tt>
-
# * (-) <tt>validate</tt>
-
# * (2) <tt>after_validation</tt>
-
# * (3) <tt>before_save</tt>
-
# * (4) <tt>before_create</tt>
-
# * (-) <tt>create</tt>
-
# * (5) <tt>after_create</tt>
-
# * (6) <tt>after_save</tt>
-
# * (7) <tt>after_commit</tt>
-
#
-
# Also, an <tt>after_rollback</tt> callback can be configured to be triggered whenever a rollback is issued.
-
# Check out <tt>ActiveRecord::Transactions</tt> for more details about <tt>after_commit</tt> and
-
# <tt>after_rollback</tt>.
-
#
-
# Lastly an <tt>after_find</tt> and <tt>after_initialize</tt> callback is triggered for each object that
-
# is found and instantiated by a finder, with <tt>after_initialize</tt> being triggered after new objects
-
# are instantiated as well.
-
#
-
# That's a total of twelve callbacks, which gives you immense power to react and prepare for each state in the
-
# Active Record life cycle. The sequence for calling <tt>Base#save</tt> for an existing record is similar,
-
# except that each <tt>_create</tt> callback is replaced by the corresponding <tt>_update</tt> callback.
-
#
-
# Examples:
-
# class CreditCard < ActiveRecord::Base
-
# # Strip everything but digits, so the user can specify "555 234 34" or
-
# # "5552-3434" and both will mean "55523434"
-
# before_validation(:on => :create) do
-
# self.number = number.gsub(/[^0-9]/, "") if attribute_present?("number")
-
# end
-
# end
-
#
-
# class Subscription < ActiveRecord::Base
-
# before_create :record_signup
-
#
-
# private
-
# def record_signup
-
# self.signed_up_on = Date.today
-
# end
-
# end
-
#
-
# class Firm < ActiveRecord::Base
-
# # Destroys the associated clients and people when the firm is destroyed
-
# before_destroy { |record| Person.destroy_all "firm_id = #{record.id}" }
-
# before_destroy { |record| Client.destroy_all "client_of = #{record.id}" }
-
# end
-
#
-
# == Inheritable callback queues
-
#
-
# Besides the overwritable callback methods, it's also possible to register callbacks through the
-
# use of the callback macros. Their main advantage is that the macros add behavior into a callback
-
# queue that is kept intact down through an inheritance hierarchy.
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy :destroy_author
-
# end
-
#
-
# class Reply < Topic
-
# before_destroy :destroy_readers
-
# end
-
#
-
# Now, when <tt>Topic#destroy</tt> is run only +destroy_author+ is called. When <tt>Reply#destroy</tt> is
-
# run, both +destroy_author+ and +destroy_readers+ are called. Contrast this to the following situation
-
# where the +before_destroy+ method is overridden:
-
#
-
# class Topic < ActiveRecord::Base
-
# def before_destroy() destroy_author end
-
# end
-
#
-
# class Reply < Topic
-
# def before_destroy() destroy_readers end
-
# end
-
#
-
# In that case, <tt>Reply#destroy</tt> would only run +destroy_readers+ and _not_ +destroy_author+.
-
# So, use the callback macros when you want to ensure that a certain callback is called for the entire
-
# hierarchy, and use the regular overwriteable methods when you want to leave it up to each descendant
-
# to decide whether they want to call +super+ and trigger the inherited callbacks.
-
#
-
# *IMPORTANT:* In order for inheritance to work for the callback queues, you must specify the
-
# callbacks before specifying the associations. Otherwise, you might trigger the loading of a
-
# child before the parent has registered the callbacks and they won't be inherited.
-
#
-
# == Types of callbacks
-
#
-
# There are four types of callbacks accepted by the callback macros: Method references (symbol), callback objects,
-
# inline methods (using a proc), and inline eval methods (using a string). Method references and callback objects
-
# are the recommended approaches, inline methods using a proc are sometimes appropriate (such as for
-
# creating mix-ins), and inline eval methods are deprecated.
-
#
-
# The method reference callbacks work by specifying a protected or private method available in the object, like this:
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy :delete_parents
-
#
-
# private
-
# def delete_parents
-
# self.class.delete_all "parent_id = #{id}"
-
# end
-
# end
-
#
-
# The callback objects have methods named after the callback called with the record as the only parameter, such as:
-
#
-
# class BankAccount < ActiveRecord::Base
-
# before_save EncryptionWrapper.new
-
# after_save EncryptionWrapper.new
-
# after_initialize EncryptionWrapper.new
-
# end
-
#
-
# class EncryptionWrapper
-
# def before_save(record)
-
# record.credit_card_number = encrypt(record.credit_card_number)
-
# end
-
#
-
# def after_save(record)
-
# record.credit_card_number = decrypt(record.credit_card_number)
-
# end
-
#
-
# alias_method :after_find, :after_save
-
#
-
# private
-
# def encrypt(value)
-
# # Secrecy is committed
-
# end
-
#
-
# def decrypt(value)
-
# # Secrecy is unveiled
-
# end
-
# end
-
#
-
# So you specify the object you want messaged on a given callback. When that callback is triggered, the object has
-
# a method by the name of the callback messaged. You can make these callbacks more flexible by passing in other
-
# initialization data such as the name of the attribute to work with:
-
#
-
# class BankAccount < ActiveRecord::Base
-
# before_save EncryptionWrapper.new("credit_card_number")
-
# after_save EncryptionWrapper.new("credit_card_number")
-
# after_initialize EncryptionWrapper.new("credit_card_number")
-
# end
-
#
-
# class EncryptionWrapper
-
# def initialize(attribute)
-
# @attribute = attribute
-
# end
-
#
-
# def before_save(record)
-
# record.send("#{@attribute}=", encrypt(record.send("#{@attribute}")))
-
# end
-
#
-
# def after_save(record)
-
# record.send("#{@attribute}=", decrypt(record.send("#{@attribute}")))
-
# end
-
#
-
# alias_method :after_find, :after_save
-
#
-
# private
-
# def encrypt(value)
-
# # Secrecy is committed
-
# end
-
#
-
# def decrypt(value)
-
# # Secrecy is unveiled
-
# end
-
# end
-
#
-
# The callback macros usually accept a symbol for the method they're supposed to run, but you can also
-
# pass a "method string", which will then be evaluated within the binding of the callback. Example:
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy 'self.class.delete_all "parent_id = #{id}"'
-
# end
-
#
-
# Notice that single quotes (') are used so the <tt>#{id}</tt> part isn't evaluated until the callback
-
# is triggered. Also note that these inline callbacks can be stacked just like the regular ones:
-
#
-
# class Topic < ActiveRecord::Base
-
# before_destroy 'self.class.delete_all "parent_id = #{id}"',
-
# 'puts "Evaluated after parents are destroyed"'
-
# end
-
#
-
# == <tt>before_validation*</tt> returning statements
-
#
-
# If the returning value of a +before_validation+ callback can be evaluated to +false+, the process will be
-
# aborted and <tt>Base#save</tt> will return +false+. If Base#save! is called it will raise a
-
# ActiveRecord::RecordInvalid exception. Nothing will be appended to the errors object.
-
#
-
# == Canceling callbacks
-
#
-
# If a <tt>before_*</tt> callback returns +false+, all the later callbacks and the associated action are
-
# cancelled. If an <tt>after_*</tt> callback returns +false+, all the later callbacks are cancelled.
-
# Callbacks are generally run in the order they are defined, with the exception of callbacks defined as
-
# methods on the model, which are called last.
-
#
-
# == Ordering callbacks
-
#
-
# Sometimes the code needs that the callbacks execute in a specific order. For example, a +before_destroy+
-
# callback (+log_children+ in this case) should be executed before the children get destroyed by the +dependent: destroy+ option.
-
#
-
# Let's look at the code below:
-
#
-
# class Topic < ActiveRecord::Base
-
# has_many :children, dependent: destroy
-
#
-
# before_destroy :log_children
-
#
-
# private
-
# def log_children
-
# # Child processing
-
# end
-
# end
-
#
-
# In this case, the problem is that when the +before_destroy+ callback is executed, the children are not available
-
# because the +destroy+ callback gets executed first. You can use the +prepend+ option on the +before_destroy+ callback to avoid this.
-
#
-
# class Topic < ActiveRecord::Base
-
# has_many :children, dependent: destroy
-
#
-
# before_destroy :log_children, prepend: true
-
#
-
# private
-
# def log_children
-
# # Child processing
-
# end
-
# end
-
#
-
# This way, the +before_destroy+ gets executed before the <tt>dependent: destroy</tt> is called, and the data is still available.
-
#
-
# == Transactions
-
#
-
# The entire callback chain of a +save+, <tt>save!</tt>, or +destroy+ call runs
-
# within a transaction. That includes <tt>after_*</tt> hooks. If everything
-
# goes fine a COMMIT is executed once the chain has been completed.
-
#
-
# If a <tt>before_*</tt> callback cancels the action a ROLLBACK is issued. You
-
# can also trigger a ROLLBACK raising an exception in any of the callbacks,
-
# including <tt>after_*</tt> hooks. Note, however, that in that case the client
-
# needs to be aware of it because an ordinary +save+ will raise such exception
-
# instead of quietly returning +false+.
-
#
-
# == Debugging callbacks
-
#
-
# The callback chain is accessible via the <tt>_*_callbacks</tt> method on an object. ActiveModel Callbacks support
-
# <tt>:before</tt>, <tt>:after</tt> and <tt>:around</tt> as values for the <tt>kind</tt> property. The <tt>kind</tt> property
-
# defines what part of the chain the callback runs in.
-
#
-
# To find all callbacks in the before_save callback chain:
-
#
-
# Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) }
-
#
-
# Returns an array of callback objects that form the before_save chain.
-
#
-
# To further check if the before_save chain contains a proc defined as <tt>rest_when_dead</tt> use the <tt>filter</tt> property of the callback object:
-
#
-
# Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) }.collect(&:filter).include?(:rest_when_dead)
-
#
-
# Returns true or false depending on whether the proc is contained in the before_save callback chain on a Topic model.
-
#
-
1
module Callbacks
-
1
extend ActiveSupport::Concern
-
-
1
CALLBACKS = [
-
:after_initialize, :after_find, :after_touch, :before_validation, :after_validation,
-
:before_save, :around_save, :after_save, :before_create, :around_create,
-
:after_create, :before_update, :around_update, :after_update,
-
:before_destroy, :around_destroy, :after_destroy, :after_commit, :after_rollback
-
]
-
-
1
module ClassMethods
-
1
include ActiveModel::Callbacks
-
end
-
-
1
included do
-
1
include ActiveModel::Validations::Callbacks
-
-
1
define_model_callbacks :initialize, :find, :touch, :only => :after
-
1
define_model_callbacks :save, :create, :update, :destroy
-
end
-
-
1
def destroy #:nodoc:
-
run_callbacks(:destroy) { super }
-
end
-
-
1
def touch(*) #:nodoc:
-
run_callbacks(:touch) { super }
-
end
-
-
1
private
-
-
1
def create_or_update #:nodoc:
-
run_callbacks(:save) { super }
-
end
-
-
1
def create #:nodoc:
-
run_callbacks(:create) { super }
-
end
-
-
1
def update(*) #:nodoc:
-
run_callbacks(:update) { super }
-
end
-
end
-
end
-
1
require 'thread'
-
1
require 'monitor'
-
1
require 'set'
-
1
require 'active_support/deprecation'
-
-
1
module ActiveRecord
-
# Raised when a connection could not be obtained within the connection
-
# acquisition timeout period: because max connections in pool
-
# are in use.
-
1
class ConnectionTimeoutError < ConnectionNotEstablished
-
end
-
-
1
module ConnectionAdapters
-
# Connection pool base class for managing Active Record database
-
# connections.
-
#
-
# == Introduction
-
#
-
# A connection pool synchronizes thread access to a limited number of
-
# database connections. The basic idea is that each thread checks out a
-
# database connection from the pool, uses that connection, and checks the
-
# connection back in. ConnectionPool is completely thread-safe, and will
-
# ensure that a connection cannot be used by two threads at the same time,
-
# as long as ConnectionPool's contract is correctly followed. It will also
-
# handle cases in which there are more threads than connections: if all
-
# connections have been checked out, and a thread tries to checkout a
-
# connection anyway, then ConnectionPool will wait until some other thread
-
# has checked in a connection.
-
#
-
# == Obtaining (checking out) a connection
-
#
-
# Connections can be obtained and used from a connection pool in several
-
# ways:
-
#
-
# 1. Simply use ActiveRecord::Base.connection as with Active Record 2.1 and
-
# earlier (pre-connection-pooling). Eventually, when you're done with
-
# the connection(s) and wish it to be returned to the pool, you call
-
# ActiveRecord::Base.clear_active_connections!. This will be the
-
# default behavior for Active Record when used in conjunction with
-
# Action Pack's request handling cycle.
-
# 2. Manually check out a connection from the pool with
-
# ActiveRecord::Base.connection_pool.checkout. You are responsible for
-
# returning this connection to the pool when finished by calling
-
# ActiveRecord::Base.connection_pool.checkin(connection).
-
# 3. Use ActiveRecord::Base.connection_pool.with_connection(&block), which
-
# obtains a connection, yields it as the sole argument to the block,
-
# and returns it to the pool after the block completes.
-
#
-
# Connections in the pool are actually AbstractAdapter objects (or objects
-
# compatible with AbstractAdapter's interface).
-
#
-
# == Options
-
#
-
# There are several connection-pooling-related options that you can add to
-
# your database connection configuration:
-
#
-
# * +pool+: number indicating size of connection pool (default 5)
-
# * +checkout_timeout+: number of seconds to block and wait for a connection
-
# before giving up and raising a timeout error (default 5 seconds).
-
# * +reaping_frequency+: frequency in seconds to periodically run the
-
# Reaper, which attempts to find and close dead connections, which can
-
# occur if a programmer forgets to close a connection at the end of a
-
# thread or a thread dies unexpectedly. (Default nil, which means don't
-
# run the Reaper).
-
# * +dead_connection_timeout+: number of seconds from last checkout
-
# after which the Reaper will consider a connection reapable. (default
-
# 5 seconds).
-
1
class ConnectionPool
-
# Threadsafe, fair, FIFO queue. Meant to be used by ConnectionPool
-
# with which it shares a Monitor. But could be a generic Queue.
-
#
-
# The Queue in stdlib's 'thread' could replace this class except
-
# stdlib's doesn't support waiting with a timeout.
-
1
class Queue
-
1
def initialize(lock = Monitor.new)
-
@lock = lock
-
@cond = @lock.new_cond
-
@num_waiting = 0
-
@queue = []
-
end
-
-
# Test if any threads are currently waiting on the queue.
-
1
def any_waiting?
-
synchronize do
-
@num_waiting > 0
-
end
-
end
-
-
# Return the number of threads currently waiting on this
-
# queue.
-
1
def num_waiting
-
synchronize do
-
@num_waiting
-
end
-
end
-
-
# Add +element+ to the queue. Never blocks.
-
1
def add(element)
-
synchronize do
-
@queue.push element
-
@cond.signal
-
end
-
end
-
-
# If +element+ is in the queue, remove and return it, or nil.
-
1
def delete(element)
-
synchronize do
-
@queue.delete(element)
-
end
-
end
-
-
# Remove all elements from the queue.
-
1
def clear
-
synchronize do
-
@queue.clear
-
end
-
end
-
-
# Remove the head of the queue.
-
#
-
# If +timeout+ is not given, remove and return the head the
-
# queue if the number of available elements is strictly
-
# greater than the number of threads currently waiting (that
-
# is, don't jump ahead in line). Otherwise, return nil.
-
#
-
# If +timeout+ is given, block if it there is no element
-
# available, waiting up to +timeout+ seconds for an element to
-
# become available.
-
#
-
# Raises:
-
# - ConnectionTimeoutError if +timeout+ is given and no element
-
# becomes available after +timeout+ seconds,
-
1
def poll(timeout = nil)
-
synchronize do
-
if timeout
-
no_wait_poll || wait_poll(timeout)
-
else
-
no_wait_poll
-
end
-
end
-
end
-
-
1
private
-
-
1
def synchronize(&block)
-
@lock.synchronize(&block)
-
end
-
-
# Test if the queue currently contains any elements.
-
1
def any?
-
!@queue.empty?
-
end
-
-
# A thread can remove an element from the queue without
-
# waiting if an only if the number of currently available
-
# connections is strictly greater than the number of waiting
-
# threads.
-
1
def can_remove_no_wait?
-
@queue.size > @num_waiting
-
end
-
-
# Removes and returns the head of the queue if possible, or nil.
-
1
def remove
-
@queue.shift
-
end
-
-
# Remove and return the head the queue if the number of
-
# available elements is strictly greater than the number of
-
# threads currently waiting. Otherwise, return nil.
-
1
def no_wait_poll
-
remove if can_remove_no_wait?
-
end
-
-
# Waits on the queue up to +timeout+ seconds, then removes and
-
# returns the head of the queue.
-
1
def wait_poll(timeout)
-
@num_waiting += 1
-
-
t0 = Time.now
-
elapsed = 0
-
loop do
-
@cond.wait(timeout - elapsed)
-
-
return remove if any?
-
-
elapsed = Time.now - t0
-
if elapsed >= timeout
-
msg = 'could not obtain a database connection within %0.3f seconds (waited %0.3f seconds)' %
-
[timeout, elapsed]
-
raise ConnectionTimeoutError, msg
-
end
-
end
-
ensure
-
@num_waiting -= 1
-
end
-
end
-
-
# Every +frequency+ seconds, the reaper will call +reap+ on +pool+.
-
# A reaper instantiated with a nil frequency will never reap the
-
# connection pool.
-
#
-
# Configure the frequency by setting "reaping_frequency" in your
-
# database yaml file.
-
1
class Reaper
-
1
attr_reader :pool, :frequency
-
-
1
def initialize(pool, frequency)
-
@pool = pool
-
@frequency = frequency
-
end
-
-
1
def run
-
return unless frequency
-
Thread.new(frequency, pool) { |t, p|
-
while true
-
sleep t
-
p.reap
-
end
-
}
-
end
-
end
-
-
1
include MonitorMixin
-
-
1
attr_accessor :automatic_reconnect, :checkout_timeout, :dead_connection_timeout
-
1
attr_reader :spec, :connections, :size, :reaper
-
-
# Creates a new ConnectionPool object. +spec+ is a ConnectionSpecification
-
# object which describes database connection information (e.g. adapter,
-
# host name, username, password, etc), as well as the maximum size for
-
# this ConnectionPool.
-
#
-
# The default ConnectionPool maximum size is 5.
-
1
def initialize(spec)
-
super()
-
-
@spec = spec
-
-
# The cache of reserved connections mapped to threads
-
@reserved_connections = {}
-
-
@checkout_timeout = spec.config[:checkout_timeout] || 5
-
@dead_connection_timeout = spec.config[:dead_connection_timeout]
-
@reaper = Reaper.new self, spec.config[:reaping_frequency]
-
@reaper.run
-
-
# default max pool size to 5
-
@size = (spec.config[:pool] && spec.config[:pool].to_i) || 5
-
-
@connections = []
-
@automatic_reconnect = true
-
-
@available = Queue.new self
-
end
-
-
# Hack for tests to be able to add connections. Do not call outside of tests
-
1
def insert_connection_for_test!(c) #:nodoc:
-
synchronize do
-
@connections << c
-
@available.add c
-
end
-
end
-
-
# Retrieve the connection associated with the current thread, or call
-
# #checkout to obtain one if necessary.
-
#
-
# #connection can be called any number of times; the connection is
-
# held in a hash keyed by the thread id.
-
1
def connection
-
synchronize do
-
@reserved_connections[current_connection_id] ||= checkout
-
end
-
end
-
-
# Is there an open connection that is being used for the current thread?
-
1
def active_connection?
-
synchronize do
-
@reserved_connections.fetch(current_connection_id) {
-
return false
-
}.in_use?
-
end
-
end
-
-
# Signal that the thread is finished with the current connection.
-
# #release_connection releases the connection-thread association
-
# and returns the connection to the pool.
-
1
def release_connection(with_id = current_connection_id)
-
synchronize do
-
conn = @reserved_connections.delete(with_id)
-
checkin conn if conn
-
end
-
end
-
-
# If a connection already exists yield it to the block. If no connection
-
# exists checkout a connection, yield it to the block, and checkin the
-
# connection when finished.
-
1
def with_connection
-
connection_id = current_connection_id
-
fresh_connection = true unless active_connection?
-
yield connection
-
ensure
-
release_connection(connection_id) if fresh_connection
-
end
-
-
# Returns true if a connection has already been opened.
-
1
def connected?
-
synchronize { @connections.any? }
-
end
-
-
# Disconnects all connections in the pool, and clears the pool.
-
1
def disconnect!
-
synchronize do
-
@reserved_connections = {}
-
@connections.each do |conn|
-
checkin conn
-
conn.disconnect!
-
end
-
@connections = []
-
@available.clear
-
end
-
end
-
-
# Clears the cache which maps classes.
-
1
def clear_reloadable_connections!
-
synchronize do
-
@reserved_connections = {}
-
@connections.each do |conn|
-
checkin conn
-
conn.disconnect! if conn.requires_reloading?
-
end
-
@connections.delete_if do |conn|
-
conn.requires_reloading?
-
end
-
@available.clear
-
@connections.each do |conn|
-
@available.add conn
-
end
-
end
-
end
-
-
1
def clear_stale_cached_connections! # :nodoc:
-
reap
-
end
-
1
deprecate :clear_stale_cached_connections! => "Please use #reap instead"
-
-
# Check-out a database connection from the pool, indicating that you want
-
# to use it. You should call #checkin when you no longer need this.
-
#
-
# This is done by either returning and leasing existing connection, or by
-
# creating a new connection and leasing it.
-
#
-
# If all connections are leased and the pool is at capacity (meaning the
-
# number of currently leased connections is greater than or equal to the
-
# size limit set), an ActiveRecord::ConnectionTimeoutError exception will be raised.
-
#
-
# Returns: an AbstractAdapter object.
-
#
-
# Raises:
-
# - ConnectionTimeoutError: no connection can be obtained from the pool.
-
1
def checkout
-
synchronize do
-
conn = acquire_connection
-
conn.lease
-
checkout_and_verify(conn)
-
end
-
end
-
-
# Check-in a database connection back into the pool, indicating that you
-
# no longer need this connection.
-
#
-
# +conn+: an AbstractAdapter object, which was obtained by earlier by
-
# calling +checkout+ on this pool.
-
1
def checkin(conn)
-
synchronize do
-
conn.run_callbacks :checkin do
-
conn.expire
-
end
-
-
release conn
-
-
@available.add conn
-
end
-
end
-
-
# Remove a connection from the connection pool. The connection will
-
# remain open and active but will no longer be managed by this pool.
-
1
def remove(conn)
-
synchronize do
-
@connections.delete conn
-
@available.delete conn
-
-
# FIXME: we might want to store the key on the connection so that removing
-
# from the reserved hash will be a little easier.
-
release conn
-
-
@available.add checkout_new_connection if @available.any_waiting?
-
end
-
end
-
-
# Removes dead connections from the pool. A dead connection can occur
-
# if a programmer forgets to close a connection at the end of a thread
-
# or a thread dies unexpectedly.
-
1
def reap
-
synchronize do
-
stale = Time.now - @dead_connection_timeout
-
connections.dup.each do |conn|
-
remove conn if conn.in_use? && stale > conn.last_use && !conn.active?
-
end
-
end
-
end
-
-
1
private
-
-
# Acquire a connection by one of 1) immediately removing one
-
# from the queue of available connections, 2) creating a new
-
# connection if the pool is not at capacity, 3) waiting on the
-
# queue for a connection to become available.
-
#
-
# Raises:
-
# - ConnectionTimeoutError if a connection could not be acquired
-
1
def acquire_connection
-
if conn = @available.poll
-
conn
-
elsif @connections.size < @size
-
checkout_new_connection
-
else
-
@available.poll(@checkout_timeout)
-
end
-
end
-
-
1
def release(conn)
-
thread_id = if @reserved_connections[current_connection_id] == conn
-
current_connection_id
-
else
-
@reserved_connections.keys.find { |k|
-
@reserved_connections[k] == conn
-
}
-
end
-
-
@reserved_connections.delete thread_id if thread_id
-
end
-
-
1
def new_connection
-
Base.send(spec.adapter_method, spec.config)
-
end
-
-
1
def current_connection_id #:nodoc:
-
Base.connection_id ||= Thread.current.object_id
-
end
-
-
1
def checkout_new_connection
-
raise ConnectionNotEstablished unless @automatic_reconnect
-
-
c = new_connection
-
c.pool = self
-
@connections << c
-
c
-
end
-
-
1
def checkout_and_verify(c)
-
c.run_callbacks :checkout do
-
c.verify!
-
end
-
c
-
end
-
end
-
-
# ConnectionHandler is a collection of ConnectionPool objects. It is used
-
# for keeping separate connection pools for Active Record models that connect
-
# to different databases.
-
#
-
# For example, suppose that you have 5 models, with the following hierarchy:
-
#
-
# |
-
# +-- Book
-
# | |
-
# | +-- ScaryBook
-
# | +-- GoodBook
-
# +-- Author
-
# +-- BankAccount
-
#
-
# Suppose that Book is to connect to a separate database (i.e. one other
-
# than the default database). Then Book, ScaryBook and GoodBook will all use
-
# the same connection pool. Likewise, Author and BankAccount will use the
-
# same connection pool. However, the connection pool used by Author/BankAccount
-
# is not the same as the one used by Book/ScaryBook/GoodBook.
-
#
-
# Normally there is only a single ConnectionHandler instance, accessible via
-
# ActiveRecord::Base.connection_handler. Active Record models use this to
-
# determine the connection pool that they should use.
-
1
class ConnectionHandler
-
1
def initialize
-
1
@owner_to_pool = Hash.new { |h,k| h[k] = {} }
-
1
@class_to_pool = Hash.new { |h,k| h[k] = {} }
-
end
-
-
1
def connection_pool_list
-
owner_to_pool.values.compact
-
end
-
-
1
def connection_pools
-
ActiveSupport::Deprecation.warn(
-
"In the next release, this will return the same as #connection_pool_list. " \
-
"(An array of pools, rather than a hash mapping specs to pools.)"
-
)
-
Hash[connection_pool_list.map { |pool| [pool.spec, pool] }]
-
end
-
-
1
def establish_connection(owner, spec)
-
@class_to_pool.clear
-
owner_to_pool[owner] = ConnectionAdapters::ConnectionPool.new(spec)
-
end
-
-
# Returns true if there are any active connections among the connection
-
# pools that the ConnectionHandler is managing.
-
1
def active_connections?
-
connection_pool_list.any?(&:active_connection?)
-
end
-
-
# Returns any connections in use by the current thread back to the pool,
-
# and also returns connections to the pool cached by threads that are no
-
# longer alive.
-
1
def clear_active_connections!
-
connection_pool_list.each(&:release_connection)
-
end
-
-
# Clears the cache which maps classes.
-
1
def clear_reloadable_connections!
-
connection_pool_list.each(&:clear_reloadable_connections!)
-
end
-
-
1
def clear_all_connections!
-
connection_pool_list.each(&:disconnect!)
-
end
-
-
# Locate the connection of the nearest super class. This can be an
-
# active or defined connection: if it is the latter, it will be
-
# opened and set as the active connection for the class it was defined
-
# for (not necessarily the current class).
-
1
def retrieve_connection(klass) #:nodoc:
-
pool = retrieve_connection_pool(klass)
-
(pool && pool.connection) or raise ConnectionNotEstablished
-
end
-
-
# Returns true if a connection that's accessible to this class has
-
# already been opened.
-
1
def connected?(klass)
-
conn = retrieve_connection_pool(klass)
-
conn && conn.connected?
-
end
-
-
# Remove the connection for this class. This will close the active
-
# connection and the defined connection (if they exist). The result
-
# can be used as an argument for establish_connection, for easily
-
# re-establishing the connection.
-
1
def remove_connection(owner)
-
if pool = owner_to_pool.delete(owner)
-
@class_to_pool.clear
-
pool.automatic_reconnect = false
-
pool.disconnect!
-
pool.spec.config
-
end
-
end
-
-
# Retrieving the connection pool happens a lot so we cache it in @class_to_pool.
-
# This makes retrieving the connection pool O(1) once the process is warm.
-
# When a connection is established or removed, we invalidate the cache.
-
#
-
# Ideally we would use #fetch here, as class_to_pool[klass] may sometimes be nil.
-
# However, benchmarking (https://gist.github.com/3552829) showed that #fetch is
-
# significantly slower than #[]. So in the nil case, no caching will take place,
-
# but that's ok since the nil case is not the common one that we wish to optimise
-
# for.
-
1
def retrieve_connection_pool(klass)
-
class_to_pool[klass] ||= begin
-
until pool = pool_for(klass)
-
klass = klass.superclass
-
break unless klass <= Base
-
end
-
-
class_to_pool[klass] = pool
-
end
-
end
-
-
1
private
-
-
1
def owner_to_pool
-
@owner_to_pool[Process.pid]
-
end
-
-
1
def class_to_pool
-
@class_to_pool[Process.pid]
-
end
-
-
1
def pool_for(owner)
-
owner_to_pool.fetch(owner) {
-
if ancestor_pool = pool_from_any_process_for(owner)
-
# A connection was established in an ancestor process that must have
-
# subsequently forked. We can't reuse the connection, but we can copy
-
# the specification and establish a new connection with it.
-
establish_connection owner, ancestor_pool.spec
-
else
-
owner_to_pool[owner] = nil
-
end
-
}
-
end
-
-
1
def pool_from_any_process_for(owner)
-
owner_to_pool = @owner_to_pool.values.find { |v| v[owner] }
-
owner_to_pool && owner_to_pool[owner]
-
end
-
end
-
-
1
class ConnectionManagement
-
1
def initialize(app)
-
@app = app
-
end
-
-
1
def call(env)
-
testing = env.key?('rack.test')
-
-
response = @app.call(env)
-
response[2] = ::Rack::BodyProxy.new(response[2]) do
-
ActiveRecord::Base.clear_active_connections! unless testing
-
end
-
-
response
-
rescue
-
ActiveRecord::Base.clear_active_connections! unless testing
-
raise
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
1
module DatabaseLimits
-
-
# Returns the maximum length of a table alias.
-
1
def table_alias_length
-
255
-
end
-
-
# Returns the maximum length of a column name.
-
1
def column_name_length
-
64
-
end
-
-
# Returns the maximum length of a table name.
-
1
def table_name_length
-
64
-
end
-
-
# Returns the maximum length of an index name.
-
1
def index_name_length
-
64
-
end
-
-
# Returns the maximum number of columns per table.
-
1
def columns_per_table
-
1024
-
end
-
-
# Returns the maximum number of indexes per table.
-
1
def indexes_per_table
-
16
-
end
-
-
# Returns the maximum number of columns in a multicolumn index.
-
1
def columns_per_multicolumn_index
-
16
-
end
-
-
# Returns the maximum number of elements in an IN (x,y,z) clause.
-
# nil means no limit.
-
1
def in_clause_length
-
nil
-
end
-
-
# Returns the maximum length of an SQL query.
-
1
def sql_query_length
-
1048575
-
end
-
-
# Returns maximum number of joins in a single query.
-
1
def joins_per_query
-
256
-
end
-
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
1
module DatabaseStatements
-
1
def initialize
-
super
-
reset_transaction
-
end
-
-
# Converts an arel AST to SQL
-
1
def to_sql(arel, binds = [])
-
if arel.respond_to?(:ast)
-
binds = binds.dup
-
visitor.accept(arel.ast) do
-
quote(*binds.shift.reverse)
-
end
-
else
-
arel
-
end
-
end
-
-
# Returns an array of record hashes with the column names as keys and
-
# column values as values.
-
1
def select_all(arel, name = nil, binds = [])
-
select(to_sql(arel, binds), name, binds)
-
end
-
-
# Returns a record hash with the column names as keys and column values
-
# as values.
-
1
def select_one(arel, name = nil, binds = [])
-
result = select_all(arel, name, binds)
-
result.first if result
-
end
-
-
# Returns a single value from a record
-
1
def select_value(arel, name = nil, binds = [])
-
if result = select_one(arel, name, binds)
-
result.values.first
-
end
-
end
-
-
# Returns an array of the values of the first column in a select:
-
# select_values("SELECT id FROM companies LIMIT 3") => [1,2,3]
-
1
def select_values(arel, name = nil)
-
result = select_rows(to_sql(arel, []), name)
-
result.map { |v| v[0] }
-
end
-
-
# Returns an array of arrays containing the field values.
-
# Order is the same as that returned by +columns+.
-
1
def select_rows(sql, name = nil)
-
end
-
1
undef_method :select_rows
-
-
# Executes the SQL statement in the context of this connection.
-
1
def execute(sql, name = nil)
-
end
-
1
undef_method :execute
-
-
# Executes +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is logged along with
-
# the executed +sql+ statement.
-
1
def exec_query(sql, name = 'SQL', binds = [])
-
end
-
-
# Executes insert +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is logged along with
-
# the executed +sql+ statement.
-
1
def exec_insert(sql, name, binds, pk = nil, sequence_name = nil)
-
exec_query(sql, name, binds)
-
end
-
-
# Executes delete +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is logged along with
-
# the executed +sql+ statement.
-
1
def exec_delete(sql, name, binds)
-
exec_query(sql, name, binds)
-
end
-
-
# Executes update +sql+ statement in the context of this connection using
-
# +binds+ as the bind substitutes. +name+ is logged along with
-
# the executed +sql+ statement.
-
1
def exec_update(sql, name, binds)
-
exec_query(sql, name, binds)
-
end
-
-
# Returns the last auto-generated ID from the affected table.
-
#
-
# +id_value+ will be returned unless the value is nil, in
-
# which case the database will attempt to calculate the last inserted
-
# id and return that value.
-
#
-
# If the next id was calculated in advance (as in Oracle), it should be
-
# passed in as +id_value+.
-
1
def insert(arel, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = [])
-
sql, binds = sql_for_insert(to_sql(arel, binds), pk, id_value, sequence_name, binds)
-
value = exec_insert(sql, name, binds, pk, sequence_name)
-
id_value || last_inserted_id(value)
-
end
-
-
# Executes the update statement and returns the number of rows affected.
-
1
def update(arel, name = nil, binds = [])
-
exec_update(to_sql(arel, binds), name, binds)
-
end
-
-
# Executes the delete statement and returns the number of rows affected.
-
1
def delete(arel, name = nil, binds = [])
-
exec_delete(to_sql(arel, binds), name, binds)
-
end
-
-
# Returns +true+ when the connection adapter supports prepared statement
-
# caching, otherwise returns +false+
-
1
def supports_statement_cache?
-
false
-
end
-
-
# Runs the given block in a database transaction, and returns the result
-
# of the block.
-
#
-
# == Nested transactions support
-
#
-
# Most databases don't support true nested transactions. At the time of
-
# writing, the only database that supports true nested transactions that
-
# we're aware of, is MS-SQL.
-
#
-
# In order to get around this problem, #transaction will emulate the effect
-
# of nested transactions, by using savepoints:
-
# http://dev.mysql.com/doc/refman/5.0/en/savepoint.html
-
# Savepoints are supported by MySQL and PostgreSQL, but not SQLite3.
-
#
-
# It is safe to call this method if a database transaction is already open,
-
# i.e. if #transaction is called within another #transaction block. In case
-
# of a nested call, #transaction will behave as follows:
-
#
-
# - The block will be run without doing anything. All database statements
-
# that happen within the block are effectively appended to the already
-
# open database transaction.
-
# - However, if +:requires_new+ is set, the block will be wrapped in a
-
# database savepoint acting as a sub-transaction.
-
#
-
# === Caveats
-
#
-
# MySQL doesn't support DDL transactions. If you perform a DDL operation,
-
# then any created savepoints will be automatically released. For example,
-
# if you've created a savepoint, then you execute a CREATE TABLE statement,
-
# then the savepoint that was created will be automatically released.
-
#
-
# This means that, on MySQL, you shouldn't execute DDL operations inside
-
# a #transaction call that you know might create a savepoint. Otherwise,
-
# #transaction will raise exceptions when it tries to release the
-
# already-automatically-released savepoints:
-
#
-
# Model.connection.transaction do # BEGIN
-
# Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1
-
# Model.connection.create_table(...)
-
# # active_record_1 now automatically released
-
# end # RELEASE SAVEPOINT active_record_1 <--- BOOM! database error!
-
# end
-
#
-
# == Transaction isolation
-
#
-
# If your database supports setting the isolation level for a transaction, you can set
-
# it like so:
-
#
-
# Post.transaction(isolation: :serializable) do
-
# # ...
-
# end
-
#
-
# Valid isolation levels are:
-
#
-
# * <tt>:read_uncommitted</tt>
-
# * <tt>:read_committed</tt>
-
# * <tt>:repeatable_read</tt>
-
# * <tt>:serializable</tt>
-
#
-
# You should consult the documentation for your database to understand the
-
# semantics of these different levels:
-
#
-
# * http://www.postgresql.org/docs/9.1/static/transaction-iso.html
-
# * https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html
-
#
-
# An <tt>ActiveRecord::TransactionIsolationError</tt> will be raised if:
-
#
-
# * The adapter does not support setting the isolation level
-
# * You are joining an existing open transaction
-
# * You are creating a nested (savepoint) transaction
-
#
-
# The mysql, mysql2 and postgresql adapters support setting the transaction
-
# isolation level. However, support is disabled for mysql versions below 5,
-
# because they are affected by a bug[http://bugs.mysql.com/bug.php?id=39170]
-
# which means the isolation level gets persisted outside the transaction.
-
1
def transaction(options = {})
-
options.assert_valid_keys :requires_new, :joinable, :isolation
-
-
if !options[:requires_new] && current_transaction.joinable?
-
if options[:isolation]
-
raise ActiveRecord::TransactionIsolationError, "cannot set isolation when joining a transaction"
-
end
-
-
yield
-
else
-
within_new_transaction(options) { yield }
-
end
-
rescue ActiveRecord::Rollback
-
# rollbacks are silently swallowed
-
end
-
-
1
def within_new_transaction(options = {}) #:nodoc:
-
transaction = begin_transaction(options)
-
yield
-
rescue Exception => error
-
rollback_transaction if transaction
-
raise
-
ensure
-
begin
-
commit_transaction unless error
-
rescue Exception
-
rollback_transaction
-
raise
-
end
-
end
-
-
1
def current_transaction #:nodoc:
-
@transaction
-
end
-
-
1
def transaction_open?
-
@transaction.open?
-
end
-
-
1
def begin_transaction(options = {}) #:nodoc:
-
@transaction = @transaction.begin(options)
-
end
-
-
1
def commit_transaction #:nodoc:
-
@transaction = @transaction.commit
-
end
-
-
1
def rollback_transaction #:nodoc:
-
@transaction = @transaction.rollback
-
end
-
-
1
def reset_transaction #:nodoc:
-
@transaction = ClosedTransaction.new(self)
-
end
-
-
# Register a record with the current transaction so that its after_commit and after_rollback callbacks
-
# can be called.
-
1
def add_transaction_record(record)
-
@transaction.add_record(record)
-
end
-
-
# Begins the transaction (and turns off auto-committing).
-
1
def begin_db_transaction() end
-
-
1
def transaction_isolation_levels
-
{
-
read_uncommitted: "READ UNCOMMITTED",
-
read_committed: "READ COMMITTED",
-
repeatable_read: "REPEATABLE READ",
-
serializable: "SERIALIZABLE"
-
}
-
end
-
-
# Begins the transaction with the isolation level set. Raises an error by
-
# default; adapters that support setting the isolation level should implement
-
# this method.
-
1
def begin_isolated_db_transaction(isolation)
-
raise ActiveRecord::TransactionIsolationError, "adapter does not support setting transaction isolation"
-
end
-
-
# Commits the transaction (and turns on auto-committing).
-
1
def commit_db_transaction() end
-
-
# Rolls back the transaction (and turns on auto-committing). Must be
-
# done if the transaction block raises an exception or returns false.
-
1
def rollback_db_transaction() end
-
-
1
def default_sequence_name(table, column)
-
nil
-
end
-
-
# Set the sequence to the max value of the table's column.
-
1
def reset_sequence!(table, column, sequence = nil)
-
# Do nothing by default. Implement for PostgreSQL, Oracle, ...
-
end
-
-
# Inserts the given fixture into the table. Overridden in adapters that require
-
# something beyond a simple insert (eg. Oracle).
-
1
def insert_fixture(fixture, table_name)
-
columns = Hash[columns(table_name).map { |c| [c.name, c] }]
-
-
key_list = []
-
value_list = fixture.map do |name, value|
-
key_list << quote_column_name(name)
-
quote(value, columns[name])
-
end
-
-
execute "INSERT INTO #{quote_table_name(table_name)} (#{key_list.join(', ')}) VALUES (#{value_list.join(', ')})", 'Fixture Insert'
-
end
-
-
1
def empty_insert_statement_value
-
"DEFAULT VALUES"
-
end
-
-
1
def case_sensitive_equality_operator
-
"="
-
end
-
-
1
def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key)
-
"WHERE #{quoted_primary_key} IN (SELECT #{quoted_primary_key} FROM #{quoted_table_name} #{where_sql})"
-
end
-
-
# Sanitizes the given LIMIT parameter in order to prevent SQL injection.
-
#
-
# The +limit+ may be anything that can evaluate to a string via #to_s. It
-
# should look like an integer, or a comma-delimited list of integers, or
-
# an Arel SQL literal.
-
#
-
# Returns Integer and Arel::Nodes::SqlLiteral limits as is.
-
# Returns the sanitized limit parameter, either as an integer, or as a
-
# string which contains a comma-delimited list of integers.
-
1
def sanitize_limit(limit)
-
if limit.is_a?(Integer) || limit.is_a?(Arel::Nodes::SqlLiteral)
-
limit
-
elsif limit.to_s =~ /,/
-
Arel.sql limit.to_s.split(',').map{ |i| Integer(i) }.join(',')
-
else
-
Integer(limit)
-
end
-
end
-
-
# The default strategy for an UPDATE with joins is to use a subquery. This doesn't work
-
# on mysql (even when aliasing the tables), but mysql allows using JOIN directly in
-
# an UPDATE statement, so in the mysql adapters we redefine this to do that.
-
1
def join_to_update(update, select) #:nodoc:
-
key = update.key
-
subselect = subquery_for(key, select)
-
-
update.where key.in(subselect)
-
end
-
-
1
def join_to_delete(delete, select, key) #:nodoc:
-
subselect = subquery_for(key, select)
-
-
delete.where key.in(subselect)
-
end
-
-
1
protected
-
-
# Return a subquery for the given key using the join information.
-
1
def subquery_for(key, select)
-
subselect = select.clone
-
subselect.projections = [key]
-
subselect
-
end
-
-
# Returns an array of record hashes with the column names as keys and
-
# column values as values.
-
1
def select(sql, name = nil, binds = [])
-
end
-
1
undef_method :select
-
-
# Returns the last auto-generated ID from the affected table.
-
1
def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
-
execute(sql, name)
-
id_value
-
end
-
-
# Executes the update statement and returns the number of rows affected.
-
1
def update_sql(sql, name = nil)
-
execute(sql, name)
-
end
-
-
# Executes the delete statement and returns the number of rows affected.
-
1
def delete_sql(sql, name = nil)
-
update_sql(sql, name)
-
end
-
-
1
def sql_for_insert(sql, pk, id_value, sequence_name, binds)
-
[sql, binds]
-
end
-
-
1
def last_inserted_id(result)
-
row = result.rows.first
-
row && row.first
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
1
module QueryCache
-
1
class << self
-
1
def included(base) #:nodoc:
-
1
dirties_query_cache base, :insert, :update, :delete
-
end
-
-
1
def dirties_query_cache(base, *method_names)
-
1
method_names.each do |method_name|
-
3
base.class_eval <<-end_code, __FILE__, __LINE__ + 1
-
def #{method_name}(*) # def update_with_query_dirty(*args)
-
clear_query_cache if @query_cache_enabled # clear_query_cache if @query_cache_enabled
-
super # update_without_query_dirty(*args)
-
end # end
-
end_code
-
end
-
end
-
end
-
-
1
attr_reader :query_cache, :query_cache_enabled
-
-
# Enable the query cache within the block.
-
1
def cache
-
old, @query_cache_enabled = @query_cache_enabled, true
-
yield
-
ensure
-
clear_query_cache
-
@query_cache_enabled = old
-
end
-
-
1
def enable_query_cache!
-
@query_cache_enabled = true
-
end
-
-
1
def disable_query_cache!
-
@query_cache_enabled = false
-
end
-
-
# Disable the query cache within the block.
-
1
def uncached
-
old, @query_cache_enabled = @query_cache_enabled, false
-
yield
-
ensure
-
@query_cache_enabled = old
-
end
-
-
# Clears the query cache.
-
#
-
# One reason you may wish to call this method explicitly is between queries
-
# that ask the database to randomize results. Otherwise the cache would see
-
# the same SQL query and repeatedly return the same result each time, silently
-
# undermining the randomness you were expecting.
-
1
def clear_query_cache
-
@query_cache.clear
-
end
-
-
1
def select_all(arel, name = nil, binds = [])
-
if @query_cache_enabled && !locked?(arel)
-
sql = to_sql(arel, binds)
-
cache_sql(sql, binds) { super(sql, name, binds) }
-
else
-
super
-
end
-
end
-
-
1
private
-
-
1
def cache_sql(sql, binds)
-
result =
-
if @query_cache[sql].key?(binds)
-
ActiveSupport::Notifications.instrument("sql.active_record",
-
:sql => sql, :binds => binds, :name => "CACHE", :connection_id => object_id)
-
@query_cache[sql][binds]
-
else
-
@query_cache[sql][binds] = yield
-
end
-
-
# FIXME: we should guarantee that all cached items are Result
-
# objects. Then we can avoid this conditional
-
if ActiveRecord::Result === result
-
result.dup
-
else
-
result.collect { |row| row.dup }
-
end
-
end
-
-
1
def locked?(arel)
-
arel.respond_to?(:locked) && arel.locked
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/big_decimal/conversions'
-
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
1
module Quoting
-
# Quotes the column value to help prevent
-
# {SQL injection attacks}[http://en.wikipedia.org/wiki/SQL_injection].
-
1
def quote(value, column = nil)
-
# records are quoted as their primary key
-
return value.quoted_id if value.respond_to?(:quoted_id)
-
-
case value
-
when String, ActiveSupport::Multibyte::Chars
-
value = value.to_s
-
return "'#{quote_string(value)}'" unless column
-
-
case column.type
-
when :binary then "'#{quote_string(column.string_to_binary(value))}'"
-
when :integer then value.to_i.to_s
-
when :float then value.to_f.to_s
-
else
-
"'#{quote_string(value)}'"
-
end
-
-
when true, false
-
if column && column.type == :integer
-
value ? '1' : '0'
-
else
-
value ? quoted_true : quoted_false
-
end
-
# BigDecimals need to be put in a non-normalized form and quoted.
-
when nil then "NULL"
-
when BigDecimal then value.to_s('F')
-
when Numeric, ActiveSupport::Duration then value.to_s
-
when Date, Time then "'#{quoted_date(value)}'"
-
when Symbol then "'#{quote_string(value.to_s)}'"
-
when Class then "'#{value.to_s}'"
-
else
-
"'#{quote_string(YAML.dump(value))}'"
-
end
-
end
-
-
# Cast a +value+ to a type that the database understands. For example,
-
# SQLite does not understand dates, so this method will convert a Date
-
# to a String.
-
1
def type_cast(value, column)
-
return value.id if value.respond_to?(:quoted_id)
-
-
case value
-
when String, ActiveSupport::Multibyte::Chars
-
value = value.to_s
-
return value unless column
-
-
case column.type
-
when :binary then value
-
when :integer then value.to_i
-
when :float then value.to_f
-
else
-
value
-
end
-
-
when true, false
-
if column && column.type == :integer
-
value ? 1 : 0
-
else
-
value ? 't' : 'f'
-
end
-
# BigDecimals need to be put in a non-normalized form and quoted.
-
when nil then nil
-
when BigDecimal then value.to_s('F')
-
when Numeric then value
-
when Date, Time then quoted_date(value)
-
when Symbol then value.to_s
-
else
-
to_type = column ? " to #{column.type}" : ""
-
raise TypeError, "can't cast #{value.class}#{to_type}"
-
end
-
end
-
-
# Quotes a string, escaping any ' (single quote) and \ (backslash)
-
# characters.
-
1
def quote_string(s)
-
s.gsub(/\\/, '\&\&').gsub(/'/, "''") # ' (for ruby-mode)
-
end
-
-
# Quotes the column name. Defaults to no quoting.
-
1
def quote_column_name(column_name)
-
column_name
-
end
-
-
# Quotes the table name. Defaults to column name quoting.
-
1
def quote_table_name(table_name)
-
quote_column_name(table_name)
-
end
-
-
1
def quoted_true
-
"'t'"
-
end
-
-
1
def quoted_false
-
"'f'"
-
end
-
-
1
def quoted_date(value)
-
if value.acts_like?(:time)
-
zone_conversion_method = ActiveRecord::Base.default_timezone == :utc ? :getutc : :getlocal
-
-
if value.respond_to?(zone_conversion_method)
-
value = value.send(zone_conversion_method)
-
end
-
end
-
-
value.to_s(:db)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
# The goal of this module is to move Adapter specific column
-
# definitions to the Adapter instead of having it in the schema
-
# dumper itself. This code represents the normal case.
-
# We can then redefine how certain data types may be handled in the schema dumper on the
-
# Adapter level by over-writing this code inside the database spececific adapters
-
1
module ColumnDumper
-
1
def column_spec(column, types)
-
spec = prepare_column_options(column, types)
-
(spec.keys - [:name, :type]).each{ |k| spec[k].insert(0, "#{k.to_s}: ")}
-
spec
-
end
-
-
# This can be overridden on a Adapter level basis to support other
-
# extended datatypes (Example: Adding an array option in the
-
# PostgreSQLAdapter)
-
1
def prepare_column_options(column, types)
-
spec = {}
-
spec[:name] = column.name.inspect
-
-
# AR has an optimization which handles zero-scale decimals as integers. This
-
# code ensures that the dumper still dumps the column as a decimal.
-
spec[:type] = if column.type == :integer && /^(numeric|decimal)/ =~ column.sql_type
-
'decimal'
-
else
-
column.type.to_s
-
end
-
spec[:limit] = column.limit.inspect if column.limit != types[column.type][:limit] && spec[:type] != 'decimal'
-
spec[:precision] = column.precision.inspect if column.precision
-
spec[:scale] = column.scale.inspect if column.scale
-
spec[:null] = 'false' unless column.null
-
spec[:default] = default_string(column.default) if column.has_default?
-
spec
-
end
-
-
# Lists the valid migration options
-
1
def migration_keys
-
[:name, :limit, :precision, :scale, :default, :null]
-
end
-
-
1
private
-
-
1
def default_string(value)
-
case value
-
when BigDecimal
-
value.to_s
-
when Date, DateTime, Time
-
"'#{value.to_s(:db)}'"
-
else
-
value.inspect
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_record/migration/join_table'
-
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
1
module SchemaStatements
-
1
include ActiveRecord::Migration::JoinTable
-
-
# Returns a Hash of mappings from the abstract data types to the native
-
# database types. See TableDefinition#column for details on the recognized
-
# abstract data types.
-
1
def native_database_types
-
{}
-
end
-
-
# Truncates a table alias according to the limits of the current adapter.
-
1
def table_alias_for(table_name)
-
table_name[0...table_alias_length].tr('.', '_')
-
end
-
-
# Checks to see if the table +table_name+ exists on the database.
-
#
-
# table_exists?(:developers)
-
1
def table_exists?(table_name)
-
tables.include?(table_name.to_s)
-
end
-
-
# Returns an array of indexes for the given table.
-
# def indexes(table_name, name = nil) end
-
-
# Checks to see if an index exists on a table for a given index definition.
-
#
-
# # Check an index exists
-
# index_exists?(:suppliers, :company_id)
-
#
-
# # Check an index on multiple columns exists
-
# index_exists?(:suppliers, [:company_id, :company_type])
-
#
-
# # Check a unique index exists
-
# index_exists?(:suppliers, :company_id, unique: true)
-
#
-
# # Check an index with a custom name exists
-
# index_exists?(:suppliers, :company_id, name: "idx_company_id"
-
1
def index_exists?(table_name, column_name, options = {})
-
column_names = Array(column_name)
-
index_name = options.key?(:name) ? options[:name].to_s : index_name(table_name, :column => column_names)
-
if options[:unique]
-
indexes(table_name).any?{ |i| i.unique && i.name == index_name }
-
else
-
indexes(table_name).any?{ |i| i.name == index_name }
-
end
-
end
-
-
# Returns an array of Column objects for the table specified by +table_name+.
-
# See the concrete implementation for details on the expected parameter values.
-
1
def columns(table_name) end
-
-
# Checks to see if a column exists in a given table.
-
#
-
# # Check a column exists
-
# column_exists?(:suppliers, :name)
-
#
-
# # Check a column exists of a particular type
-
# column_exists?(:suppliers, :name, :string)
-
#
-
# # Check a column exists with a specific definition
-
# column_exists?(:suppliers, :name, :string, limit: 100)
-
# column_exists?(:suppliers, :name, :string, default: 'default')
-
# column_exists?(:suppliers, :name, :string, null: false)
-
# column_exists?(:suppliers, :tax, :decimal, precision: 8, scale: 2)
-
1
def column_exists?(table_name, column_name, type = nil, options = {})
-
columns(table_name).any?{ |c| c.name == column_name.to_s &&
-
(!type || c.type == type) &&
-
(!options.key?(:limit) || c.limit == options[:limit]) &&
-
(!options.key?(:precision) || c.precision == options[:precision]) &&
-
(!options.key?(:scale) || c.scale == options[:scale]) &&
-
(!options.key?(:default) || c.default == options[:default]) &&
-
(!options.key?(:null) || c.null == options[:null]) }
-
end
-
-
# Creates a new table with the name +table_name+. +table_name+ may either
-
# be a String or a Symbol.
-
#
-
# There are two ways to work with +create_table+. You can use the block
-
# form or the regular form, like this:
-
#
-
# === Block form
-
# # create_table() passes a TableDefinition object to the block.
-
# # This form will not only create the table, but also columns for the
-
# # table.
-
#
-
# create_table(:suppliers) do |t|
-
# t.column :name, :string, limit: 60
-
# # Other fields here
-
# end
-
#
-
# === Block form, with shorthand
-
# # You can also use the column types as method calls, rather than calling the column method.
-
# create_table(:suppliers) do |t|
-
# t.string :name, limit: 60
-
# # Other fields here
-
# end
-
#
-
# === Regular form
-
# # Creates a table called 'suppliers' with no columns.
-
# create_table(:suppliers)
-
# # Add a column to 'suppliers'.
-
# add_column(:suppliers, :name, :string, {limit: 60})
-
#
-
# The +options+ hash can include the following keys:
-
# [<tt>:id</tt>]
-
# Whether to automatically add a primary key column. Defaults to true.
-
# Join tables for +has_and_belongs_to_many+ should set it to false.
-
# [<tt>:primary_key</tt>]
-
# The name of the primary key, if one is to be added automatically.
-
# Defaults to +id+. If <tt>:id</tt> is false this option is ignored.
-
#
-
# Also note that this just sets the primary key in the table. You additionally
-
# need to configure the primary key in the model via +self.primary_key=+.
-
# Models do NOT auto-detect the primary key from their table definition.
-
#
-
# [<tt>:options</tt>]
-
# Any extra options you want appended to the table definition.
-
# [<tt>:temporary</tt>]
-
# Make a temporary table.
-
# [<tt>:force</tt>]
-
# Set to true to drop the table before creating it.
-
# Defaults to false.
-
#
-
# ====== Add a backend specific option to the generated SQL (MySQL)
-
# create_table(:suppliers, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8')
-
# generates:
-
# CREATE TABLE suppliers (
-
# id int(11) DEFAULT NULL auto_increment PRIMARY KEY
-
# ) ENGINE=InnoDB DEFAULT CHARSET=utf8
-
#
-
# ====== Rename the primary key column
-
# create_table(:objects, primary_key: 'guid') do |t|
-
# t.column :name, :string, limit: 80
-
# end
-
# generates:
-
# CREATE TABLE objects (
-
# guid int(11) DEFAULT NULL auto_increment PRIMARY KEY,
-
# name varchar(80)
-
# )
-
#
-
# ====== Do not add a primary key column
-
# create_table(:categories_suppliers, id: false) do |t|
-
# t.column :category_id, :integer
-
# t.column :supplier_id, :integer
-
# end
-
# generates:
-
# CREATE TABLE categories_suppliers (
-
# category_id int,
-
# supplier_id int
-
# )
-
#
-
# See also TableDefinition#column for details on how to create columns.
-
1
def create_table(table_name, options = {})
-
td = table_definition
-
td.primary_key(options[:primary_key] || Base.get_primary_key(table_name.to_s.singularize)) unless options[:id] == false
-
-
yield td if block_given?
-
-
if options[:force] && table_exists?(table_name)
-
drop_table(table_name, options)
-
end
-
-
create_sql = "CREATE#{' TEMPORARY' if options[:temporary]} TABLE "
-
create_sql << "#{quote_table_name(table_name)} ("
-
create_sql << td.to_sql
-
create_sql << ") #{options[:options]}"
-
execute create_sql
-
td.indexes.each_pair { |c,o| add_index table_name, c, o }
-
end
-
-
# Creates a new join table with the name created using the lexical order of the first two
-
# arguments. These arguments can be a String or a Symbol.
-
#
-
# # Creates a table called 'assemblies_parts' with no id.
-
# create_join_table(:assemblies, :parts)
-
#
-
# You can pass a +options+ hash can include the following keys:
-
# [<tt>:table_name</tt>]
-
# Sets the table name overriding the default
-
# [<tt>:column_options</tt>]
-
# Any extra options you want appended to the columns definition.
-
# [<tt>:options</tt>]
-
# Any extra options you want appended to the table definition.
-
# [<tt>:temporary</tt>]
-
# Make a temporary table.
-
# [<tt>:force</tt>]
-
# Set to true to drop the table before creating it.
-
# Defaults to false.
-
#
-
# ====== Add a backend specific option to the generated SQL (MySQL)
-
# create_join_table(:assemblies, :parts, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8')
-
# generates:
-
# CREATE TABLE assemblies_parts (
-
# assembly_id int NOT NULL,
-
# part_id int NOT NULL,
-
# ) ENGINE=InnoDB DEFAULT CHARSET=utf8
-
1
def create_join_table(table_1, table_2, options = {})
-
join_table_name = find_join_table_name(table_1, table_2, options)
-
-
column_options = options.delete(:column_options) || {}
-
column_options.reverse_merge!(null: false)
-
-
t1_column, t2_column = [table_1, table_2].map{ |t| t.to_s.singularize.foreign_key }
-
-
create_table(join_table_name, options.merge!(id: false)) do |td|
-
td.integer t1_column, column_options
-
td.integer t2_column, column_options
-
yield td if block_given?
-
end
-
end
-
-
# A block for changing columns in +table+.
-
#
-
# # change_table() yields a Table instance
-
# change_table(:suppliers) do |t|
-
# t.column :name, :string, limit: 60
-
# # Other column alterations here
-
# end
-
#
-
# The +options+ hash can include the following keys:
-
# [<tt>:bulk</tt>]
-
# Set this to true to make this a bulk alter query, such as
-
# ALTER TABLE `users` ADD COLUMN age INT(11), ADD COLUMN birthdate DATETIME ...
-
#
-
# Defaults to false.
-
#
-
# ====== Add a column
-
# change_table(:suppliers) do |t|
-
# t.column :name, :string, limit: 60
-
# end
-
#
-
# ====== Add 2 integer columns
-
# change_table(:suppliers) do |t|
-
# t.integer :width, :height, null: false, default: 0
-
# end
-
#
-
# ====== Add created_at/updated_at columns
-
# change_table(:suppliers) do |t|
-
# t.timestamps
-
# end
-
#
-
# ====== Add a foreign key column
-
# change_table(:suppliers) do |t|
-
# t.references :company
-
# end
-
#
-
# Creates a <tt>company_id(integer)</tt> column
-
#
-
# ====== Add a polymorphic foreign key column
-
# change_table(:suppliers) do |t|
-
# t.belongs_to :company, polymorphic: true
-
# end
-
#
-
# Creates <tt>company_type(varchar)</tt> and <tt>company_id(integer)</tt> columns
-
#
-
# ====== Remove a column
-
# change_table(:suppliers) do |t|
-
# t.remove :company
-
# end
-
#
-
# ====== Remove several columns
-
# change_table(:suppliers) do |t|
-
# t.remove :company_id
-
# t.remove :width, :height
-
# end
-
#
-
# ====== Remove an index
-
# change_table(:suppliers) do |t|
-
# t.remove_index :company_id
-
# end
-
#
-
# See also Table for details on
-
# all of the various column transformation
-
1
def change_table(table_name, options = {})
-
if supports_bulk_alter? && options[:bulk]
-
recorder = ActiveRecord::Migration::CommandRecorder.new(self)
-
yield Table.new(table_name, recorder)
-
bulk_change_table(table_name, recorder.commands)
-
else
-
yield Table.new(table_name, self)
-
end
-
end
-
-
# Renames a table.
-
#
-
# rename_table('octopuses', 'octopi')
-
1
def rename_table(table_name, new_name)
-
raise NotImplementedError, "rename_table is not implemented"
-
end
-
-
# Drops a table from the database.
-
1
def drop_table(table_name, options = {})
-
execute "DROP TABLE #{quote_table_name(table_name)}"
-
end
-
-
# Adds a new column to the named table.
-
# See TableDefinition#column for details of the options you can use.
-
1
def add_column(table_name, column_name, type, options = {})
-
add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
-
add_column_options!(add_column_sql, options)
-
execute(add_column_sql)
-
end
-
-
# Removes the column(s) from the table definition.
-
#
-
# remove_column(:suppliers, :qualification)
-
# remove_columns(:suppliers, :qualification, :experience)
-
1
def remove_column(table_name, *column_names)
-
columns_for_remove(table_name, *column_names).each {|column_name| execute "ALTER TABLE #{quote_table_name(table_name)} DROP #{column_name}" }
-
end
-
1
alias :remove_columns :remove_column
-
-
# Changes the column's definition according to the new options.
-
# See TableDefinition#column for details of the options you can use.
-
#
-
# change_column(:suppliers, :name, :string, limit: 80)
-
# change_column(:accounts, :description, :text)
-
1
def change_column(table_name, column_name, type, options = {})
-
raise NotImplementedError, "change_column is not implemented"
-
end
-
-
# Sets a new default value for a column.
-
#
-
# change_column_default(:suppliers, :qualification, 'new')
-
# change_column_default(:accounts, :authorized, 1)
-
# change_column_default(:users, :email, nil)
-
1
def change_column_default(table_name, column_name, default)
-
raise NotImplementedError, "change_column_default is not implemented"
-
end
-
-
# Renames a column.
-
#
-
# rename_column(:suppliers, :description, :name)
-
1
def rename_column(table_name, column_name, new_column_name)
-
raise NotImplementedError, "rename_column is not implemented"
-
end
-
-
# Adds a new index to the table. +column_name+ can be a single Symbol, or
-
# an Array of Symbols.
-
#
-
# The index will be named after the table and the column name(s), unless
-
# you pass <tt>:name</tt> as an option.
-
#
-
# ====== Creating a simple index
-
# add_index(:suppliers, :name)
-
# generates
-
# CREATE INDEX suppliers_name_index ON suppliers(name)
-
#
-
# ====== Creating a unique index
-
# add_index(:accounts, [:branch_id, :party_id], unique: true)
-
# generates
-
# CREATE UNIQUE INDEX accounts_branch_id_party_id_index ON accounts(branch_id, party_id)
-
#
-
# ====== Creating a named index
-
# add_index(:accounts, [:branch_id, :party_id], unique: true, name: 'by_branch_party')
-
# generates
-
# CREATE UNIQUE INDEX by_branch_party ON accounts(branch_id, party_id)
-
#
-
# ====== Creating an index with specific key length
-
# add_index(:accounts, :name, name: 'by_name', length: 10)
-
# generates
-
# CREATE INDEX by_name ON accounts(name(10))
-
#
-
# add_index(:accounts, [:name, :surname], name: 'by_name_surname', length: {name: 10, surname: 15})
-
# generates
-
# CREATE INDEX by_name_surname ON accounts(name(10), surname(15))
-
#
-
# Note: SQLite doesn't support index length
-
#
-
# ====== Creating an index with a sort order (desc or asc, asc is the default)
-
# add_index(:accounts, [:branch_id, :party_id, :surname], order: {branch_id: :desc, party_id: :asc})
-
# generates
-
# CREATE INDEX by_branch_desc_party ON accounts(branch_id DESC, party_id ASC, surname)
-
#
-
# Note: mysql doesn't yet support index order (it accepts the syntax but ignores it)
-
#
-
# ====== Creating a partial index
-
# add_index(:accounts, [:branch_id, :party_id], unique: true, where: "active")
-
# generates
-
# CREATE UNIQUE INDEX index_accounts_on_branch_id_and_party_id ON accounts(branch_id, party_id) WHERE active
-
#
-
# Note: only supported by PostgreSQL
-
#
-
1
def add_index(table_name, column_name, options = {})
-
index_name, index_type, index_columns, index_options = add_index_options(table_name, column_name, options)
-
execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} (#{index_columns})#{index_options}"
-
end
-
-
# Remove the given index from the table.
-
#
-
# Remove the index_accounts_on_column in the accounts table.
-
# remove_index :accounts, :column
-
# Remove the index named index_accounts_on_branch_id in the accounts table.
-
# remove_index :accounts, column: :branch_id
-
# Remove the index named index_accounts_on_branch_id_and_party_id in the accounts table.
-
# remove_index :accounts, column: [:branch_id, :party_id]
-
# Remove the index named by_branch_party in the accounts table.
-
# remove_index :accounts, name: :by_branch_party
-
1
def remove_index(table_name, options = {})
-
remove_index!(table_name, index_name_for_remove(table_name, options))
-
end
-
-
1
def remove_index!(table_name, index_name) #:nodoc:
-
execute "DROP INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)}"
-
end
-
-
# Rename an index.
-
#
-
# Rename the index_people_on_last_name index to index_users_on_last_name
-
# rename_index :people, 'index_people_on_last_name', 'index_users_on_last_name'
-
1
def rename_index(table_name, old_name, new_name)
-
# this is a naive implementation; some DBs may support this more efficiently (Postgres, for instance)
-
old_index_def = indexes(table_name).detect { |i| i.name == old_name }
-
return unless old_index_def
-
remove_index(table_name, :name => old_name)
-
add_index(table_name, old_index_def.columns, :name => new_name, :unique => old_index_def.unique)
-
end
-
-
1
def index_name(table_name, options) #:nodoc:
-
if Hash === options
-
if options[:column]
-
"index_#{table_name}_on_#{Array(options[:column]) * '_and_'}"
-
elsif options[:name]
-
options[:name]
-
else
-
raise ArgumentError, "You must specify the index name"
-
end
-
else
-
index_name(table_name, :column => options)
-
end
-
end
-
-
# Verify the existence of an index with a given name.
-
#
-
# The default argument is returned if the underlying implementation does not define the indexes method,
-
# as there's no way to determine the correct answer in that case.
-
1
def index_name_exists?(table_name, index_name, default)
-
return default unless respond_to?(:indexes)
-
index_name = index_name.to_s
-
indexes(table_name).detect { |i| i.name == index_name }
-
end
-
-
# Adds a reference. Optionally adds a +type+ column, if <tt>:polymorphic</tt> option is provided.
-
# <tt>add_reference</tt> and <tt>add_belongs_to</tt> are acceptable.
-
#
-
# ====== Create a user_id column
-
# add_reference(:products, :user)
-
#
-
# ====== Create a supplier_id and supplier_type columns
-
# add_belongs_to(:products, :supplier, polymorphic: true)
-
#
-
# ====== Create a supplier_id, supplier_type columns and appropriate index
-
# add_reference(:products, :supplier, polymorphic: true, index: true)
-
#
-
1
def add_reference(table_name, ref_name, options = {})
-
polymorphic = options.delete(:polymorphic)
-
index_options = options.delete(:index)
-
add_column(table_name, "#{ref_name}_id", :integer, options)
-
add_column(table_name, "#{ref_name}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) if polymorphic
-
add_index(table_name, polymorphic ? %w[id type].map{ |t| "#{ref_name}_#{t}" } : "#{ref_name}_id", index_options.is_a?(Hash) ? index_options : nil) if index_options
-
end
-
1
alias :add_belongs_to :add_reference
-
-
# Removes the reference(s). Also removes a +type+ column if one exists.
-
# <tt>remove_reference</tt>, <tt>remove_references</tt> and <tt>remove_belongs_to</tt> are acceptable.
-
#
-
# ====== Remove the reference
-
# remove_reference(:products, :user, index: true)
-
#
-
# ====== Remove polymorphic reference
-
# remove_reference(:products, :supplier, polymorphic: true)
-
#
-
1
def remove_reference(table_name, ref_name, options = {})
-
remove_column(table_name, "#{ref_name}_id")
-
remove_column(table_name, "#{ref_name}_type") if options[:polymorphic]
-
end
-
1
alias :remove_belongs_to :remove_reference
-
-
# Returns a string of <tt>CREATE TABLE</tt> SQL statement(s) for recreating the
-
# entire structure of the database.
-
1
def structure_dump
-
end
-
-
1
def dump_schema_information #:nodoc:
-
sm_table = ActiveRecord::Migrator.schema_migrations_table_name
-
-
ActiveRecord::SchemaMigration.order('version').map { |sm|
-
"INSERT INTO #{sm_table} (version) VALUES ('#{sm.version}');"
-
}.join "\n\n"
-
end
-
-
# Should not be called normally, but this operation is non-destructive.
-
# The migrations module handles this automatically.
-
1
def initialize_schema_migrations_table
-
ActiveRecord::SchemaMigration.create_table
-
end
-
-
1
def assume_migrated_upto_version(version, migrations_paths = ActiveRecord::Migrator.migrations_paths)
-
migrations_paths = Array(migrations_paths)
-
version = version.to_i
-
sm_table = quote_table_name(ActiveRecord::Migrator.schema_migrations_table_name)
-
-
migrated = select_values("SELECT version FROM #{sm_table}").map { |v| v.to_i }
-
paths = migrations_paths.map {|p| "#{p}/[0-9]*_*.rb" }
-
versions = Dir[*paths].map do |filename|
-
filename.split('/').last.split('_').first.to_i
-
end
-
-
unless migrated.include?(version)
-
execute "INSERT INTO #{sm_table} (version) VALUES ('#{version}')"
-
end
-
-
inserted = Set.new
-
(versions - migrated).each do |v|
-
if inserted.include?(v)
-
raise "Duplicate migration #{v}. Please renumber your migrations to resolve the conflict."
-
elsif v < version
-
execute "INSERT INTO #{sm_table} (version) VALUES ('#{v}')"
-
inserted << v
-
end
-
end
-
end
-
-
1
def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc:
-
if native = native_database_types[type.to_sym]
-
column_type_sql = (native.is_a?(Hash) ? native[:name] : native).dup
-
-
if type == :decimal # ignore limit, use precision and scale
-
scale ||= native[:scale]
-
-
if precision ||= native[:precision]
-
if scale
-
column_type_sql << "(#{precision},#{scale})"
-
else
-
column_type_sql << "(#{precision})"
-
end
-
elsif scale
-
raise ArgumentError, "Error adding decimal column: precision cannot be empty if scale if specified"
-
end
-
-
elsif (type != :primary_key) && (limit ||= native.is_a?(Hash) && native[:limit])
-
column_type_sql << "(#{limit})"
-
end
-
-
column_type_sql
-
else
-
type
-
end
-
end
-
-
1
def add_column_options!(sql, options) #:nodoc:
-
sql << " DEFAULT #{quote(options[:default], options[:column])}" if options_include_default?(options)
-
# must explicitly check for :null to allow change_column to work on migrations
-
if options[:null] == false
-
sql << " NOT NULL"
-
end
-
end
-
-
# SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
-
# Both PostgreSQL and Oracle overrides this for custom DISTINCT syntax.
-
#
-
# distinct("posts.id", "posts.created_at desc")
-
1
def distinct(columns, order_by)
-
"DISTINCT #{columns}"
-
end
-
-
# Adds timestamps (created_at and updated_at) columns to the named table.
-
#
-
# add_timestamps(:suppliers)
-
1
def add_timestamps(table_name)
-
add_column table_name, :created_at, :datetime
-
add_column table_name, :updated_at, :datetime
-
end
-
-
# Removes the timestamp columns (created_at and updated_at) from the table definition.
-
#
-
# remove_timestamps(:suppliers)
-
1
def remove_timestamps(table_name)
-
remove_column table_name, :updated_at
-
remove_column table_name, :created_at
-
end
-
-
1
protected
-
1
def add_index_sort_order(option_strings, column_names, options = {})
-
if options.is_a?(Hash) && order = options[:order]
-
case order
-
when Hash
-
column_names.each {|name| option_strings[name] += " #{order[name].upcase}" if order.has_key?(name)}
-
when String
-
column_names.each {|name| option_strings[name] += " #{order.upcase}"}
-
end
-
end
-
-
return option_strings
-
end
-
-
# Overridden by the mysql adapter for supporting index lengths
-
1
def quoted_columns_for_index(column_names, options = {})
-
option_strings = Hash[column_names.map {|name| [name, '']}]
-
-
# add index sort order if supported
-
if supports_index_sort_order?
-
option_strings = add_index_sort_order(option_strings, column_names, options)
-
end
-
-
column_names.map {|name| quote_column_name(name) + option_strings[name]}
-
end
-
-
1
def options_include_default?(options)
-
options.include?(:default) && !(options[:null] == false && options[:default].nil?)
-
end
-
-
1
def add_index_options(table_name, column_name, options = {})
-
column_names = Array(column_name)
-
index_name = index_name(table_name, column: column_names)
-
-
if Hash === options # legacy support, since this param was a string
-
options.assert_valid_keys(:unique, :order, :name, :where, :length)
-
-
index_type = options[:unique] ? "UNIQUE" : ""
-
index_name = options[:name].to_s if options.key?(:name)
-
-
if supports_partial_index?
-
index_options = options[:where] ? " WHERE #{options[:where]}" : ""
-
end
-
else
-
if options
-
message = "Passing a string as third argument of `add_index` is deprecated and will" +
-
" be removed in Rails 4.1." +
-
" Use add_index(#{table_name.inspect}, #{column_name.inspect}, unique: true) instead"
-
-
ActiveSupport::Deprecation.warn message
-
end
-
-
index_type = options
-
end
-
-
if index_name.length > index_name_length
-
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' is too long; the limit is #{index_name_length} characters"
-
end
-
if index_name_exists?(table_name, index_name, false)
-
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' already exists"
-
end
-
index_columns = quoted_columns_for_index(column_names, options).join(", ")
-
-
[index_name, index_type, index_columns, index_options]
-
end
-
-
1
def index_name_for_remove(table_name, options = {})
-
index_name = index_name(table_name, options)
-
-
unless index_name_exists?(table_name, index_name, true)
-
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' does not exist"
-
end
-
-
index_name
-
end
-
-
1
def columns_for_remove(table_name, *column_names)
-
raise ArgumentError.new("You must specify at least one column name. Example: remove_column(:people, :first_name)") if column_names.blank?
-
column_names.map {|column_name| quote_column_name(column_name) }
-
end
-
-
1
private
-
1
def table_definition
-
TableDefinition.new(self)
-
end
-
end
-
end
-
end
-
1
require 'date'
-
1
require 'bigdecimal'
-
1
require 'bigdecimal/util'
-
1
require 'active_support/core_ext/benchmark'
-
1
require 'active_record/connection_adapters/schema_cache'
-
1
require 'active_record/connection_adapters/abstract/schema_dumper'
-
1
require 'monitor'
-
1
require 'active_support/deprecation'
-
-
1
module ActiveRecord
-
1
module ConnectionAdapters # :nodoc:
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Column
-
1
autoload :ConnectionSpecification
-
-
1
autoload_at 'active_record/connection_adapters/abstract/schema_definitions' do
-
1
autoload :IndexDefinition
-
1
autoload :ColumnDefinition
-
1
autoload :TableDefinition
-
1
autoload :Table
-
end
-
-
1
autoload_at 'active_record/connection_adapters/abstract/connection_pool' do
-
1
autoload :ConnectionHandler
-
1
autoload :ConnectionManagement
-
end
-
-
1
autoload_under 'abstract' do
-
1
autoload :SchemaStatements
-
1
autoload :DatabaseStatements
-
1
autoload :DatabaseLimits
-
1
autoload :Quoting
-
1
autoload :ConnectionPool
-
1
autoload :QueryCache
-
end
-
-
1
autoload_at 'active_record/connection_adapters/abstract/transaction' do
-
1
autoload :ClosedTransaction
-
1
autoload :RealTransaction
-
1
autoload :SavepointTransaction
-
end
-
-
# Active Record supports multiple database systems. AbstractAdapter and
-
# related classes form the abstraction layer which makes this possible.
-
# An AbstractAdapter represents a connection to a database, and provides an
-
# abstract interface for database-specific functionality such as establishing
-
# a connection, escaping values, building the right SQL fragments for ':offset'
-
# and ':limit' options, etc.
-
#
-
# All the concrete database adapters follow the interface laid down in this class.
-
# ActiveRecord::Base.connection returns an AbstractAdapter object, which
-
# you can use.
-
#
-
# Most of the methods in the adapter are useful during migrations. Most
-
# notably, the instance methods provided by SchemaStatement are very useful.
-
1
class AbstractAdapter
-
1
include Quoting, DatabaseStatements, SchemaStatements
-
1
include DatabaseLimits
-
1
include QueryCache
-
1
include ActiveSupport::Callbacks
-
1
include MonitorMixin
-
1
include ColumnDumper
-
-
1
define_callbacks :checkout, :checkin
-
-
1
attr_accessor :visitor, :pool
-
1
attr_reader :schema_cache, :last_use, :in_use, :logger
-
1
alias :in_use? :in_use
-
-
1
def initialize(connection, logger = nil, pool = nil) #:nodoc:
-
super()
-
-
@connection = connection
-
@in_use = false
-
@instrumenter = ActiveSupport::Notifications.instrumenter
-
@last_use = false
-
@logger = logger
-
@pool = pool
-
@query_cache = Hash.new { |h,sql| h[sql] = {} }
-
@query_cache_enabled = false
-
@schema_cache = SchemaCache.new self
-
@visitor = nil
-
end
-
-
1
def lease
-
synchronize do
-
unless in_use
-
@in_use = true
-
@last_use = Time.now
-
end
-
end
-
end
-
-
1
def schema_cache=(cache)
-
cache.connection = self
-
@schema_cache = cache
-
end
-
-
1
def expire
-
@in_use = false
-
end
-
-
# Returns the human-readable name of the adapter. Use mixed case - one
-
# can always use downcase if needed.
-
1
def adapter_name
-
'Abstract'
-
end
-
-
# Does this adapter support migrations? Backend specific, as the
-
# abstract adapter always returns +false+.
-
1
def supports_migrations?
-
false
-
end
-
-
# Can this adapter determine the primary key for tables not attached
-
# to an Active Record class, such as join tables? Backend specific, as
-
# the abstract adapter always returns +false+.
-
1
def supports_primary_key?
-
false
-
end
-
-
# Does this adapter support using DISTINCT within COUNT? This is +true+
-
# for all adapters except sqlite.
-
1
def supports_count_distinct?
-
true
-
end
-
-
# Does this adapter support DDL rollbacks in transactions? That is, would
-
# CREATE TABLE or ALTER TABLE get rolled back by a transaction? PostgreSQL,
-
# SQL Server, and others support this. MySQL and others do not.
-
1
def supports_ddl_transactions?
-
false
-
end
-
-
1
def supports_bulk_alter?
-
false
-
end
-
-
# Does this adapter support savepoints? PostgreSQL and MySQL do,
-
# SQLite < 3.6.8 does not.
-
1
def supports_savepoints?
-
false
-
end
-
-
# Should primary key values be selected from their corresponding
-
# sequence before the insert statement? If true, next_sequence_value
-
# is called before each insert to set the record's primary key.
-
# This is false for all adapters but Firebird.
-
1
def prefetch_primary_key?(table_name = nil)
-
false
-
end
-
-
# Does this adapter support index sort order?
-
1
def supports_index_sort_order?
-
false
-
end
-
-
# Does this adapter support partial indices?
-
1
def supports_partial_index?
-
false
-
end
-
-
# Does this adapter support explain? As of this writing sqlite3,
-
# mysql2, and postgresql are the only ones that do.
-
1
def supports_explain?
-
false
-
end
-
-
# Does this adapter support setting the isolation level for a transaction?
-
1
def supports_transaction_isolation?
-
false
-
end
-
-
# QUOTING ==================================================
-
-
# Returns a bind substitution value given a +column+ and list of current
-
# +binds+
-
1
def substitute_at(column, index)
-
Arel::Nodes::BindParam.new '?'
-
end
-
-
# REFERENTIAL INTEGRITY ====================================
-
-
# Override to turn off referential integrity while executing <tt>&block</tt>.
-
1
def disable_referential_integrity
-
yield
-
end
-
-
# CONNECTION MANAGEMENT ====================================
-
-
# Checks whether the connection to the database is still active. This includes
-
# checking whether the database is actually capable of responding, i.e. whether
-
# the connection isn't stale.
-
1
def active?
-
end
-
-
# Disconnects from the database if already connected, and establishes a
-
# new connection with the database. Implementors should call super if they
-
# override the default implementation.
-
1
def reconnect!
-
clear_cache!
-
reset_transaction
-
end
-
-
# Disconnects from the database if already connected. Otherwise, this
-
# method does nothing.
-
1
def disconnect!
-
clear_cache!
-
reset_transaction
-
end
-
-
# Reset the state of this connection, directing the DBMS to clear
-
# transactions and other connection-related server-side state. Usually a
-
# database-dependent operation.
-
#
-
# The default implementation does nothing; the implementation should be
-
# overridden by concrete adapters.
-
1
def reset!
-
# this should be overridden by concrete adapters
-
end
-
-
###
-
# Clear any caching the database adapter may be doing, for example
-
# clearing the prepared statement cache. This is database specific.
-
1
def clear_cache!
-
# this should be overridden by concrete adapters
-
end
-
-
# Returns true if its required to reload the connection between requests for development mode.
-
# This is not the case for Ruby/MySQL and it's not necessary for any adapters except SQLite.
-
1
def requires_reloading?
-
false
-
end
-
-
# Checks whether the connection to the database is still active (i.e. not stale).
-
# This is done under the hood by calling <tt>active?</tt>. If the connection
-
# is no longer active, then this method will reconnect to the database.
-
1
def verify!(*ignored)
-
reconnect! unless active?
-
end
-
-
# Provides access to the underlying database driver for this adapter. For
-
# example, this method returns a Mysql object in case of MysqlAdapter,
-
# and a PGconn object in case of PostgreSQLAdapter.
-
#
-
# This is useful for when you need to call a proprietary method such as
-
# PostgreSQL's lo_* methods.
-
1
def raw_connection
-
@connection
-
end
-
-
1
def open_transactions
-
@transaction.number
-
end
-
-
1
def increment_open_transactions
-
ActiveSupport::Deprecation.warn "#increment_open_transactions is deprecated and has no effect"
-
end
-
-
1
def decrement_open_transactions
-
ActiveSupport::Deprecation.warn "#decrement_open_transactions is deprecated and has no effect"
-
end
-
-
1
def transaction_joinable=(joinable)
-
message = "#transaction_joinable= is deprecated. Please pass the :joinable option to #begin_transaction instead."
-
ActiveSupport::Deprecation.warn message
-
@transaction.joinable = joinable
-
end
-
-
1
def create_savepoint
-
end
-
-
1
def rollback_to_savepoint
-
end
-
-
1
def release_savepoint
-
end
-
-
1
def case_sensitive_modifier(node)
-
node
-
end
-
-
1
def case_insensitive_comparison(table, attribute, column, value)
-
table[attribute].lower.eq(table.lower(value))
-
end
-
-
1
def current_savepoint_name
-
"active_record_#{open_transactions}"
-
end
-
-
# Check the connection back in to the connection pool
-
1
def close
-
pool.checkin self
-
end
-
-
1
protected
-
-
1
def log(sql, name = "SQL", binds = [])
-
@instrumenter.instrument(
-
"sql.active_record",
-
:sql => sql,
-
:name => name,
-
:connection_id => object_id,
-
:binds => binds) { yield }
-
rescue => e
-
message = "#{e.class.name}: #{e.message}: #{sql}"
-
@logger.error message if @logger
-
exception = translate_exception(e, message)
-
exception.set_backtrace e.backtrace
-
raise exception
-
end
-
-
1
def translate_exception(exception, message)
-
# override in derived class
-
ActiveRecord::StatementInvalid.new(message)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionAdapters
-
1
class SchemaCache
-
1
attr_reader :columns, :columns_hash, :primary_keys, :tables, :version
-
1
attr_accessor :connection
-
-
1
def initialize(conn)
-
@connection = conn
-
-
@columns = {}
-
@columns_hash = {}
-
@primary_keys = {}
-
@tables = {}
-
prepare_default_proc
-
end
-
-
# A cached lookup for table existence.
-
1
def table_exists?(name)
-
return @tables[name] if @tables.key? name
-
-
@tables[name] = connection.table_exists?(name)
-
end
-
-
# Add internal cache for table with +table_name+.
-
1
def add(table_name)
-
if table_exists?(table_name)
-
@primary_keys[table_name]
-
@columns[table_name]
-
@columns_hash[table_name]
-
end
-
end
-
-
# Clears out internal caches
-
1
def clear!
-
@columns.clear
-
@columns_hash.clear
-
@primary_keys.clear
-
@tables.clear
-
@version = nil
-
end
-
-
# Clear out internal caches for table with +table_name+.
-
1
def clear_table_cache!(table_name)
-
@columns.delete table_name
-
@columns_hash.delete table_name
-
@primary_keys.delete table_name
-
@tables.delete table_name
-
end
-
-
1
def marshal_dump
-
# if we get current version during initialization, it happens stack over flow.
-
@version = ActiveRecord::Migrator.current_version
-
[@version] + [:@columns, :@columns_hash, :@primary_keys, :@tables].map do |val|
-
self.instance_variable_get(val).inject({}) { |h, v| h[v[0]] = v[1]; h }
-
end
-
end
-
-
1
def marshal_load(array)
-
@version, @columns, @columns_hash, @primary_keys, @tables = array
-
prepare_default_proc
-
end
-
-
1
private
-
-
1
def prepare_default_proc
-
@columns.default_proc = Proc.new do |h, table_name|
-
h[table_name] = connection.columns(table_name)
-
end
-
-
@columns_hash.default_proc = Proc.new do |h, table_name|
-
h[table_name] = Hash[columns[table_name].map { |col|
-
[col.name, col]
-
}]
-
end
-
-
@primary_keys.default_proc = Proc.new do |h, table_name|
-
h[table_name] = table_exists?(table_name) ? connection.primary_key(table_name) : nil
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ConnectionHandling
-
# Establishes the connection to the database. Accepts a hash as input where
-
# the <tt>:adapter</tt> key must be specified with the name of a database adapter (in lower-case)
-
# example for regular databases (MySQL, Postgresql, etc):
-
#
-
# ActiveRecord::Base.establish_connection(
-
# :adapter => "mysql",
-
# :host => "localhost",
-
# :username => "myuser",
-
# :password => "mypass",
-
# :database => "somedatabase"
-
# )
-
#
-
# Example for SQLite database:
-
#
-
# ActiveRecord::Base.establish_connection(
-
# :adapter => "sqlite",
-
# :database => "path/to/dbfile"
-
# )
-
#
-
# Also accepts keys as strings (for parsing from YAML for example):
-
#
-
# ActiveRecord::Base.establish_connection(
-
# "adapter" => "sqlite",
-
# "database" => "path/to/dbfile"
-
# )
-
#
-
# Or a URL:
-
#
-
# ActiveRecord::Base.establish_connection(
-
# "postgres://myuser:mypass@localhost/somedatabase"
-
# )
-
#
-
# The exceptions AdapterNotSpecified, AdapterNotFound and ArgumentError
-
# may be returned on an error.
-
1
def establish_connection(spec = ENV["DATABASE_URL"])
-
resolver = ConnectionAdapters::ConnectionSpecification::Resolver.new spec, configurations
-
spec = resolver.spec
-
-
unless respond_to?(spec.adapter_method)
-
raise AdapterNotFound, "database configuration specifies nonexistent #{spec.config[:adapter]} adapter"
-
end
-
-
remove_connection
-
connection_handler.establish_connection self, spec
-
end
-
-
# Returns the connection currently associated with the class. This can
-
# also be used to "borrow" the connection to do database work unrelated
-
# to any of the specific Active Records.
-
1
def connection
-
retrieve_connection
-
end
-
-
1
def connection_id
-
Thread.current['ActiveRecord::Base.connection_id']
-
end
-
-
1
def connection_id=(connection_id)
-
Thread.current['ActiveRecord::Base.connection_id'] = connection_id
-
end
-
-
# Returns the configuration of the associated connection as a hash:
-
#
-
# ActiveRecord::Base.connection_config
-
# # => {:pool=>5, :timeout=>5000, :database=>"db/development.sqlite3", :adapter=>"sqlite3"}
-
#
-
# Please use only for reading.
-
1
def connection_config
-
connection_pool.spec.config
-
end
-
-
1
def connection_pool
-
connection_handler.retrieve_connection_pool(self) or raise ConnectionNotEstablished
-
end
-
-
1
def retrieve_connection
-
connection_handler.retrieve_connection(self)
-
end
-
-
# Returns true if Active Record is connected.
-
1
def connected?
-
connection_handler.connected?(self)
-
end
-
-
1
def remove_connection(klass = self)
-
connection_handler.remove_connection(klass)
-
end
-
-
1
def clear_cache! # :nodoc:
-
connection.schema_cache.clear!
-
end
-
-
1
delegate :clear_active_connections!, :clear_reloadable_connections!,
-
:clear_all_connections!, :to => :connection_handler
-
end
-
end
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
1
require 'active_support/core_ext/object/duplicable'
-
1
require 'thread'
-
-
1
module ActiveRecord
-
1
module Core
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
##
-
# :singleton-method:
-
#
-
# Accepts a logger conforming to the interface of Log4r which is then
-
# passed on to any new database connections made and which can be
-
# retrieved on both a class and instance level by calling +logger+.
-
1
mattr_accessor :logger, instance_writer: false
-
-
##
-
# :singleton-method:
-
# Contains the database configuration - as is typically stored in config/database.yml -
-
# as a Hash.
-
#
-
# For example, the following database.yml...
-
#
-
# development:
-
# adapter: sqlite3
-
# database: db/development.sqlite3
-
#
-
# production:
-
# adapter: sqlite3
-
# database: db/production.sqlite3
-
#
-
# ...would result in ActiveRecord::Base.configurations to look like this:
-
#
-
# {
-
# 'development' => {
-
# 'adapter' => 'sqlite3',
-
# 'database' => 'db/development.sqlite3'
-
# },
-
# 'production' => {
-
# 'adapter' => 'sqlite3',
-
# 'database' => 'db/production.sqlite3'
-
# }
-
# }
-
1
mattr_accessor :configurations, instance_writer: false
-
1
self.configurations = {}
-
-
##
-
# :singleton-method:
-
# Determines whether to use Time.utc (using :utc) or Time.local (using :local) when pulling
-
# dates and times from the database. This is set to :utc by default.
-
1
mattr_accessor :default_timezone, instance_writer: false
-
1
self.default_timezone = :utc
-
-
##
-
# :singleton-method:
-
# Specifies the format to use when dumping the database schema with Rails'
-
# Rakefile. If :sql, the schema is dumped as (potentially database-
-
# specific) SQL statements. If :ruby, the schema is dumped as an
-
# ActiveRecord::Schema file which can be loaded into any database that
-
# supports migrations. Use :ruby if you want to have different database
-
# adapters for, e.g., your development and test environments.
-
1
mattr_accessor :schema_format, instance_writer: false
-
1
self.schema_format = :ruby
-
-
##
-
# :singleton-method:
-
# Specify whether or not to use timestamps for migration versions
-
1
mattr_accessor :timestamped_migrations, instance_writer: false
-
1
self.timestamped_migrations = true
-
-
1
class_attribute :connection_handler, instance_writer: false
-
1
self.connection_handler = ConnectionAdapters::ConnectionHandler.new
-
end
-
-
1
module ClassMethods
-
1
def inherited(child_class) #:nodoc:
-
1
child_class.initialize_generated_modules
-
1
super
-
end
-
-
1
def initialize_generated_modules
-
1
@attribute_methods_mutex = Mutex.new
-
-
# force attribute methods to be higher in inheritance hierarchy than other generated methods
-
1
generated_attribute_methods
-
1
generated_feature_methods
-
end
-
-
1
def generated_feature_methods
-
@generated_feature_methods ||= begin
-
1
mod = const_set(:GeneratedFeatureMethods, Module.new)
-
1
include mod
-
1
mod
-
1
end
-
end
-
-
# Returns a string like 'Post(id:integer, title:string, body:text)'
-
1
def inspect
-
if self == Base
-
super
-
elsif abstract_class?
-
"#{super}(abstract)"
-
elsif table_exists?
-
attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', '
-
"#{super}(#{attr_list})"
-
else
-
"#{super}(Table doesn't exist)"
-
end
-
end
-
-
# Overwrite the default class equality method to provide support for association proxies.
-
1
def ===(object)
-
object.is_a?(self)
-
end
-
-
# Returns an instance of <tt>Arel::Table</tt> loaded with the current table name.
-
#
-
# class Post < ActiveRecord::Base
-
# scope :published_and_commented, published.and(self.arel_table[:comments_count].gt(0))
-
# end
-
1
def arel_table
-
@arel_table ||= Arel::Table.new(table_name, arel_engine)
-
end
-
-
# Returns the Arel engine.
-
1
def arel_engine
-
@arel_engine ||= begin
-
if Base == self || connection_handler.retrieve_connection_pool(self)
-
self
-
else
-
superclass.arel_engine
-
end
-
end
-
end
-
-
1
private
-
-
1
def relation #:nodoc:
-
relation = Relation.new(self, arel_table)
-
-
if finder_needs_type_condition?
-
relation.where(type_condition).create_with(inheritance_column.to_sym => sti_name)
-
else
-
relation
-
end
-
end
-
end
-
-
# New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
-
# attributes but not yet saved (pass a hash with key names matching the associated table column names).
-
# In both instances, valid attribute keys are determined by the column names of the associated table --
-
# hence you can't have attributes that aren't part of the table columns.
-
#
-
# ==== Example:
-
# # Instantiates a single new object
-
# User.new(:first_name => 'Jamie')
-
1
def initialize(attributes = nil)
-
defaults = self.class.column_defaults.dup
-
defaults.each { |k, v| defaults[k] = v.dup if v.duplicable? }
-
-
@attributes = self.class.initialize_attributes(defaults)
-
@columns_hash = self.class.column_types.dup
-
-
init_internals
-
ensure_proper_type
-
populate_with_current_scope_attributes
-
-
assign_attributes(attributes) if attributes
-
-
yield self if block_given?
-
run_callbacks :initialize unless _initialize_callbacks.empty?
-
end
-
-
# Initialize an empty model object from +coder+. +coder+ must contain
-
# the attributes necessary for initializing an empty model object. For
-
# example:
-
#
-
# class Post < ActiveRecord::Base
-
# end
-
#
-
# post = Post.allocate
-
# post.init_with('attributes' => { 'title' => 'hello world' })
-
# post.title # => 'hello world'
-
1
def init_with(coder)
-
@attributes = self.class.initialize_attributes(coder['attributes'])
-
@columns_hash = self.class.column_types.merge(coder['column_types'] || {})
-
-
init_internals
-
-
@new_record = false
-
-
run_callbacks :find
-
run_callbacks :initialize
-
-
self
-
end
-
-
##
-
# :method: clone
-
# Identical to Ruby's clone method. This is a "shallow" copy. Be warned that your attributes are not copied.
-
# That means that modifying attributes of the clone will modify the original, since they will both point to the
-
# same attributes hash. If you need a copy of your attributes hash, please use the #dup method.
-
#
-
# user = User.first
-
# new_user = user.clone
-
# user.name # => "Bob"
-
# new_user.name = "Joe"
-
# user.name # => "Joe"
-
#
-
# user.object_id == new_user.object_id # => false
-
# user.name.object_id == new_user.name.object_id # => true
-
#
-
# user.name.object_id == user.dup.name.object_id # => false
-
-
##
-
# :method: dup
-
# Duped objects have no id assigned and are treated as new records. Note
-
# that this is a "shallow" copy as it copies the object's attributes
-
# only, not its associations. The extent of a "deep" copy is application
-
# specific and is therefore left to the application to implement according
-
# to its need.
-
# The dup method does not preserve the timestamps (created|updated)_(at|on).
-
-
##
-
1
def initialize_dup(other) # :nodoc:
-
cloned_attributes = other.clone_attributes(:read_attribute_before_type_cast)
-
self.class.initialize_attributes(cloned_attributes, :serialized => false)
-
-
@attributes = cloned_attributes
-
@attributes[self.class.primary_key] = nil
-
-
run_callbacks(:initialize) unless _initialize_callbacks.empty?
-
-
@changed_attributes = {}
-
self.class.column_defaults.each do |attr, orig_value|
-
@changed_attributes[attr] = orig_value if _field_changed?(attr, orig_value, @attributes[attr])
-
end
-
-
@aggregation_cache = {}
-
@association_cache = {}
-
@attributes_cache = {}
-
-
@new_record = true
-
-
ensure_proper_type
-
populate_with_current_scope_attributes
-
super
-
end
-
-
# Populate +coder+ with attributes about this record that should be
-
# serialized. The structure of +coder+ defined in this method is
-
# guaranteed to match the structure of +coder+ passed to the +init_with+
-
# method.
-
#
-
# Example:
-
#
-
# class Post < ActiveRecord::Base
-
# end
-
# coder = {}
-
# Post.new.encode_with(coder)
-
# coder # => {"attributes" => {"id" => nil, ... }}
-
1
def encode_with(coder)
-
coder['attributes'] = attributes
-
end
-
-
# Returns true if +comparison_object+ is the same exact object, or +comparison_object+
-
# is of the same type and +self+ has an ID and it is equal to +comparison_object.id+.
-
#
-
# Note that new records are different from any other record by definition, unless the
-
# other record is the receiver itself. Besides, if you fetch existing records with
-
# +select+ and leave the ID out, you're on your own, this predicate will return false.
-
#
-
# Note also that destroying a record preserves its ID in the model instance, so deleted
-
# models are still comparable.
-
1
def ==(comparison_object)
-
super ||
-
comparison_object.instance_of?(self.class) &&
-
id.present? &&
-
comparison_object.id == id
-
end
-
1
alias :eql? :==
-
-
# Delegates to id in order to allow two records of the same type and id to work with something like:
-
# [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
-
1
def hash
-
id.hash
-
end
-
-
# Freeze the attributes hash such that associations are still accessible, even on destroyed records.
-
1
def freeze
-
@attributes.freeze
-
self
-
end
-
-
# Returns +true+ if the attributes hash has been frozen.
-
1
def frozen?
-
@attributes.frozen?
-
end
-
-
# Allows sort on objects
-
1
def <=>(other_object)
-
if other_object.is_a?(self.class)
-
self.to_key <=> other_object.to_key
-
end
-
end
-
-
# Returns +true+ if the record is read only. Records loaded through joins with piggy-back
-
# attributes will be marked as read only since they cannot be saved.
-
1
def readonly?
-
@readonly
-
end
-
-
# Marks this record as read only.
-
1
def readonly!
-
@readonly = true
-
end
-
-
# Returns the connection currently associated with the class. This can
-
# also be used to "borrow" the connection to do database work that isn't
-
# easily done without going straight to SQL.
-
1
def connection
-
self.class.connection
-
end
-
-
# Returns the contents of the record as a nicely formatted string.
-
1
def inspect
-
inspection = if @attributes
-
self.class.column_names.collect { |name|
-
if has_attribute?(name)
-
"#{name}: #{attribute_for_inspect(name)}"
-
end
-
}.compact.join(", ")
-
else
-
"not initialized"
-
end
-
"#<#{self.class} #{inspection}>"
-
end
-
-
# Returns a hash of the given methods with their names as keys and returned values as values.
-
1
def slice(*methods)
-
Hash[methods.map { |method| [method, public_send(method)] }].with_indifferent_access
-
end
-
-
1
private
-
-
# Under Ruby 1.9, Array#flatten will call #to_ary (recursively) on each of the elements
-
# of the array, and then rescues from the possible NoMethodError. If those elements are
-
# ActiveRecord::Base's, then this triggers the various method_missing's that we have,
-
# which significantly impacts upon performance.
-
#
-
# So we can avoid the method_missing hit by explicitly defining #to_ary as nil here.
-
#
-
# See also http://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary.html
-
1
def to_ary # :nodoc:
-
nil
-
end
-
-
1
def init_internals
-
pk = self.class.primary_key
-
@attributes[pk] = nil unless @attributes.key?(pk)
-
-
@aggregation_cache = {}
-
@association_cache = {}
-
@attributes_cache = {}
-
@previously_changed = {}
-
@changed_attributes = {}
-
@readonly = false
-
@destroyed = false
-
@marked_for_destruction = false
-
@new_record = true
-
@txn = nil
-
@_start_transaction_state = {}
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record Counter Cache
-
1
module CounterCache
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
# Resets one or more counter caches to their correct value using an SQL
-
# count query. This is useful when adding new counter caches, or if the
-
# counter has been corrupted or modified directly by SQL.
-
#
-
# ==== Parameters
-
#
-
# * +id+ - The id of the object you wish to reset a counter on.
-
# * +counters+ - One or more counter names to reset
-
#
-
# ==== Examples
-
#
-
# # For Post with id #1 records reset the comments_count
-
# Post.reset_counters(1, :comments)
-
1
def reset_counters(id, *counters)
-
object = find(id)
-
counters.each do |association|
-
has_many_association = reflect_on_association(association.to_sym)
-
-
if has_many_association.is_a? ActiveRecord::Reflection::ThroughReflection
-
has_many_association = has_many_association.through_reflection
-
end
-
-
foreign_key = has_many_association.foreign_key.to_s
-
child_class = has_many_association.klass
-
belongs_to = child_class.reflect_on_all_associations(:belongs_to)
-
reflection = belongs_to.find { |e| e.foreign_key.to_s == foreign_key && e.options[:counter_cache].present? }
-
counter_name = reflection.counter_cache_column
-
-
stmt = unscoped.where(arel_table[primary_key].eq(object.id)).arel.compile_update({
-
arel_table[counter_name] => object.send(association).count
-
})
-
connection.update stmt
-
end
-
return true
-
end
-
-
# A generic "counter updater" implementation, intended primarily to be
-
# used by increment_counter and decrement_counter, but which may also
-
# be useful on its own. It simply does a direct SQL update for the record
-
# with the given ID, altering the given hash of counters by the amount
-
# given by the corresponding value:
-
#
-
# ==== Parameters
-
#
-
# * +id+ - The id of the object you wish to update a counter on or an Array of ids.
-
# * +counters+ - An Array of Hashes containing the names of the fields
-
# to update as keys and the amount to update the field by as values.
-
#
-
# ==== Examples
-
#
-
# # For the Post with id of 5, decrement the comment_count by 1, and
-
# # increment the action_count by 1
-
# Post.update_counters 5, :comment_count => -1, :action_count => 1
-
# # Executes the following SQL:
-
# # UPDATE posts
-
# # SET comment_count = COALESCE(comment_count, 0) - 1,
-
# # action_count = COALESCE(action_count, 0) + 1
-
# # WHERE id = 5
-
#
-
# # For the Posts with id of 10 and 15, increment the comment_count by 1
-
# Post.update_counters [10, 15], :comment_count => 1
-
# # Executes the following SQL:
-
# # UPDATE posts
-
# # SET comment_count = COALESCE(comment_count, 0) + 1
-
# # WHERE id IN (10, 15)
-
1
def update_counters(id, counters)
-
updates = counters.map do |counter_name, value|
-
operator = value < 0 ? '-' : '+'
-
quoted_column = connection.quote_column_name(counter_name)
-
"#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{value.abs}"
-
end
-
-
where(primary_key => id).update_all updates.join(', ')
-
end
-
-
# Increment a number field by one, usually representing a count.
-
#
-
# This is used for caching aggregate values, so that they don't need to be computed every time.
-
# For example, a DiscussionBoard may cache post_count and comment_count otherwise every time the board is
-
# shown it would have to run an SQL query to find how many posts and comments there are.
-
#
-
# ==== Parameters
-
#
-
# * +counter_name+ - The name of the field that should be incremented.
-
# * +id+ - The id of the object that should be incremented.
-
#
-
# ==== Examples
-
#
-
# # Increment the post_count column for the record with an id of 5
-
# DiscussionBoard.increment_counter(:post_count, 5)
-
1
def increment_counter(counter_name, id)
-
update_counters(id, counter_name => 1)
-
end
-
-
# Decrement a number field by one, usually representing a count.
-
#
-
# This works the same as increment_counter but reduces the column value by 1 instead of increasing it.
-
#
-
# ==== Parameters
-
#
-
# * +counter_name+ - The name of the field that should be decremented.
-
# * +id+ - The id of the object that should be decremented.
-
#
-
# ==== Examples
-
#
-
# # Decrement the post_count column for the record with an id of 5
-
# DiscussionBoard.decrement_counter(:post_count, 5)
-
1
def decrement_counter(counter_name, id)
-
update_counters(id, counter_name => -1)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module DynamicMatchers #:nodoc:
-
# This code in this file seems to have a lot of indirection, but the indirection
-
# is there to provide extension points for the activerecord-deprecated_finders
-
# gem. When we stop supporting activerecord-deprecated_finders (from Rails 5),
-
# then we can remove the indirection.
-
-
1
def respond_to?(name, include_private = false)
-
match = Method.match(self, name)
-
match && match.valid? || super
-
end
-
-
1
private
-
-
1
def method_missing(name, *arguments, &block)
-
match = Method.match(self, name)
-
-
if match && match.valid?
-
match.define
-
send(name, *arguments, &block)
-
else
-
super
-
end
-
end
-
-
1
class Method
-
1
@matchers = []
-
-
1
class << self
-
1
attr_reader :matchers
-
-
1
def match(model, name)
-
klass = matchers.find { |k| name =~ k.pattern }
-
klass.new(model, name) if klass
-
end
-
-
1
def pattern
-
/^#{prefix}_([_a-zA-Z]\w*)#{suffix}$/
-
end
-
-
1
def prefix
-
raise NotImplementedError
-
end
-
-
1
def suffix
-
''
-
end
-
end
-
-
1
attr_reader :model, :name, :attribute_names
-
-
1
def initialize(model, name)
-
@model = model
-
@name = name.to_s
-
@attribute_names = @name.match(self.class.pattern)[1].split('_and_')
-
@attribute_names.map! { |n| @model.attribute_aliases[n] || n }
-
end
-
-
1
def valid?
-
attribute_names.all? { |name| model.columns_hash[name] || model.reflect_on_aggregation(name.to_sym) }
-
end
-
-
1
def define
-
model.class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def self.#{name}(#{signature})
-
#{body}
-
end
-
CODE
-
end
-
-
1
def body
-
raise NotImplementedError
-
end
-
end
-
-
1
module Finder
-
# Extended in activerecord-deprecated_finders
-
1
def body
-
result
-
end
-
-
# Extended in activerecord-deprecated_finders
-
1
def result
-
"#{finder}(#{attributes_hash})"
-
end
-
-
# Extended in activerecord-deprecated_finders
-
1
def signature
-
attribute_names.join(', ')
-
end
-
-
1
def attributes_hash
-
"{" + attribute_names.map { |name| ":#{name} => #{name}" }.join(',') + "}"
-
end
-
-
1
def finder
-
raise NotImplementedError
-
end
-
end
-
-
1
class FindBy < Method
-
1
Method.matchers << self
-
1
include Finder
-
-
1
def self.prefix
-
"find_by"
-
end
-
-
1
def finder
-
"find_by"
-
end
-
end
-
-
1
class FindByBang < Method
-
1
Method.matchers << self
-
1
include Finder
-
-
1
def self.prefix
-
"find_by"
-
end
-
-
1
def self.suffix
-
"!"
-
end
-
-
1
def finder
-
"find_by!"
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
-
# = Active Record Errors
-
#
-
# Generic Active Record exception class.
-
1
class ActiveRecordError < StandardError
-
end
-
-
# Raised when the single-table inheritance mechanism fails to locate the subclass
-
# (for example due to improper usage of column that +inheritance_column+ points to).
-
1
class SubclassNotFound < ActiveRecordError #:nodoc:
-
end
-
-
# Raised when an object assigned to an association has an incorrect type.
-
#
-
# class Ticket < ActiveRecord::Base
-
# has_many :patches
-
# end
-
#
-
# class Patch < ActiveRecord::Base
-
# belongs_to :ticket
-
# end
-
#
-
# # Comments are not patches, this assignment raises AssociationTypeMismatch.
-
# @ticket.patches << Comment.new(:content => "Please attach tests to your patch.")
-
1
class AssociationTypeMismatch < ActiveRecordError
-
end
-
-
# Raised when unserialized object's type mismatches one specified for serializable field.
-
1
class SerializationTypeMismatch < ActiveRecordError
-
end
-
-
# Raised when adapter not specified on connection (or configuration file <tt>config/database.yml</tt>
-
# misses adapter field).
-
1
class AdapterNotSpecified < ActiveRecordError
-
end
-
-
# Raised when Active Record cannot find database adapter specified in <tt>config/database.yml</tt> or programmatically.
-
1
class AdapterNotFound < ActiveRecordError
-
end
-
-
# Raised when connection to the database could not been established (for example when <tt>connection=</tt>
-
# is given a nil object).
-
1
class ConnectionNotEstablished < ActiveRecordError
-
end
-
-
# Raised when Active Record cannot find record by given id or set of ids.
-
1
class RecordNotFound < ActiveRecordError
-
end
-
-
# Raised by ActiveRecord::Base.save! and ActiveRecord::Base.create! methods when record cannot be
-
# saved because record is invalid.
-
1
class RecordNotSaved < ActiveRecordError
-
end
-
-
# Raised by ActiveRecord::Base.destroy! when a call to destroy would return false.
-
1
class RecordNotDestroyed < ActiveRecordError
-
end
-
-
# Raised when SQL statement cannot be executed by the database (for example, it's often the case for
-
# MySQL when Ruby driver used is too old).
-
1
class StatementInvalid < ActiveRecordError
-
end
-
-
# Raised when SQL statement is invalid and the application gets a blank result.
-
1
class ThrowResult < ActiveRecordError
-
end
-
-
# Parent class for all specific exceptions which wrap database driver exceptions
-
# provides access to the original exception also.
-
1
class WrappedDatabaseException < StatementInvalid
-
1
attr_reader :original_exception
-
-
1
def initialize(message, original_exception)
-
super(message)
-
@original_exception = original_exception
-
end
-
end
-
-
# Raised when a record cannot be inserted because it would violate a uniqueness constraint.
-
1
class RecordNotUnique < WrappedDatabaseException
-
end
-
-
# Raised when a record cannot be inserted or updated because it references a non-existent record.
-
1
class InvalidForeignKey < WrappedDatabaseException
-
end
-
-
# Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example,
-
# when using +find+ method)
-
# does not match number of expected variables.
-
#
-
# For example, in
-
#
-
# Location.where("lat = ? AND lng = ?", 53.7362)
-
#
-
# two placeholders are given but only one variable to fill them.
-
1
class PreparedStatementInvalid < ActiveRecordError
-
end
-
-
# Raised on attempt to save stale record. Record is stale when it's being saved in another query after
-
# instantiation, for example, when two users edit the same wiki page and one starts editing and saves
-
# the page before the other.
-
#
-
# Read more about optimistic locking in ActiveRecord::Locking module RDoc.
-
1
class StaleObjectError < ActiveRecordError
-
1
attr_reader :record, :attempted_action
-
-
1
def initialize(record, attempted_action)
-
super("Attempted to #{attempted_action} a stale object: #{record.class.name}")
-
@record = record
-
@attempted_action = attempted_action
-
end
-
-
end
-
-
# Raised when association is being configured improperly or
-
# user tries to use offset and limit together with has_many or has_and_belongs_to_many associations.
-
1
class ConfigurationError < ActiveRecordError
-
end
-
-
# Raised on attempt to update record that is instantiated as read only.
-
1
class ReadOnlyRecord < ActiveRecordError
-
end
-
-
# ActiveRecord::Transactions::ClassMethods.transaction uses this exception
-
# to distinguish a deliberate rollback from other exceptional situations.
-
# Normally, raising an exception will cause the +transaction+ method to rollback
-
# the database transaction *and* pass on the exception. But if you raise an
-
# ActiveRecord::Rollback exception, then the database transaction will be rolled back,
-
# without passing on the exception.
-
#
-
# For example, you could do this in your controller to rollback a transaction:
-
#
-
# class BooksController < ActionController::Base
-
# def create
-
# Book.transaction do
-
# book = Book.new(params[:book])
-
# book.save!
-
# if today_is_friday?
-
# # The system must fail on Friday so that our support department
-
# # won't be out of job. We silently rollback this transaction
-
# # without telling the user.
-
# raise ActiveRecord::Rollback, "Call tech support!"
-
# end
-
# end
-
# # ActiveRecord::Rollback is the only exception that won't be passed on
-
# # by ActiveRecord::Base.transaction, so this line will still be reached
-
# # even on Friday.
-
# redirect_to root_url
-
# end
-
# end
-
1
class Rollback < ActiveRecordError
-
end
-
-
# Raised when attribute has a name reserved by Active Record (when attribute has name of one of Active Record instance methods).
-
1
class DangerousAttributeError < ActiveRecordError
-
end
-
-
# Raised when unknown attributes are supplied via mass assignment.
-
1
class UnknownAttributeError < NoMethodError
-
end
-
-
# Raised when an error occurred while doing a mass assignment to an attribute through the
-
# <tt>attributes=</tt> method. The exception has an +attribute+ property that is the name of the
-
# offending attribute.
-
1
class AttributeAssignmentError < ActiveRecordError
-
1
attr_reader :exception, :attribute
-
1
def initialize(message, exception, attribute)
-
super(message)
-
@exception = exception
-
@attribute = attribute
-
end
-
end
-
-
# Raised when there are multiple errors while doing a mass assignment through the +attributes+
-
# method. The exception has an +errors+ property that contains an array of AttributeAssignmentError
-
# objects, each corresponding to the error while assigning to an attribute.
-
1
class MultiparameterAssignmentErrors < ActiveRecordError
-
1
attr_reader :errors
-
1
def initialize(errors)
-
@errors = errors
-
end
-
end
-
-
# Raised when a primary key is needed, but there is not one specified in the schema or model.
-
1
class UnknownPrimaryKey < ActiveRecordError
-
1
attr_reader :model
-
-
1
def initialize(model)
-
super("Unknown primary key for table #{model.table_name} in model #{model}.")
-
@model = model
-
end
-
-
end
-
-
# Raised when a relation cannot be mutated because it's already loaded.
-
#
-
# class Task < ActiveRecord::Base
-
# end
-
#
-
# relation = Task.all
-
# relation.loaded? # => true
-
#
-
# # Methods which try to mutate a loaded relation fail.
-
# relation.where!(title: 'TODO') # => ActiveRecord::ImmutableRelation
-
# relation.limit!(5) # => ActiveRecord::ImmutableRelation
-
1
class ImmutableRelation < ActiveRecordError
-
end
-
-
1
class TransactionIsolationError < ActiveRecordError
-
end
-
end
-
1
require 'active_support/lazy_load_hooks'
-
-
1
module ActiveRecord
-
1
module Explain
-
1
def self.extended(base)
-
1
base.mattr_accessor :auto_explain_threshold_in_seconds, instance_accessor: false
-
end
-
-
# If auto explain is enabled, this method triggers EXPLAIN logging for the
-
# queries triggered by the block if it takes more than the threshold as a
-
# whole. That is, the threshold is not checked against each individual
-
# query, but against the duration of the entire block. This approach is
-
# convenient for relations.
-
#
-
# The available_queries_for_explain thread variable collects the queries
-
# to be explained. If the value is nil, it means queries are not being
-
# currently collected. A false value indicates collecting is turned
-
# off. Otherwise it is an array of queries.
-
1
def logging_query_plan # :nodoc:
-
return yield unless logger
-
-
threshold = auto_explain_threshold_in_seconds
-
current = Thread.current
-
if threshold && current[:available_queries_for_explain].nil?
-
begin
-
queries = current[:available_queries_for_explain] = []
-
start = Time.now
-
result = yield
-
logger.warn(exec_explain(queries)) if Time.now - start > threshold
-
result
-
ensure
-
current[:available_queries_for_explain] = nil
-
end
-
else
-
yield
-
end
-
end
-
-
# Relation#explain needs to be able to collect the queries regardless of
-
# whether auto explain is enabled. This method serves that purpose.
-
1
def collecting_queries_for_explain # :nodoc:
-
current = Thread.current
-
original, current[:available_queries_for_explain] = current[:available_queries_for_explain], []
-
return yield, current[:available_queries_for_explain]
-
ensure
-
# Note that the return value above does not depend on this assigment.
-
current[:available_queries_for_explain] = original
-
end
-
-
# Makes the adapter execute EXPLAIN for the tuples of queries and bindings.
-
# Returns a formatted string ready to be logged.
-
1
def exec_explain(queries) # :nodoc:
-
str = queries && queries.map do |sql, bind|
-
[].tap do |msg|
-
msg << "EXPLAIN for: #{sql}"
-
unless bind.empty?
-
bind_msg = bind.map {|col, val| [col.name, val]}.inspect
-
msg.last << " #{bind_msg}"
-
end
-
msg << connection.explain(sql, bind)
-
end.join("\n")
-
end.join("\n")
-
-
# Overriding inspect to be more human readable, specially in the console.
-
def str.inspect
-
self
-
end
-
str
-
end
-
-
# Silences automatic EXPLAIN logging for the duration of the block.
-
#
-
# This has high priority, no EXPLAINs will be run even if downwards
-
# the threshold is set to 0.
-
#
-
# As the name of the method suggests this only applies to automatic
-
# EXPLAINs, manual calls to <tt>ActiveRecord::Relation#explain</tt> run.
-
1
def silence_auto_explain
-
current = Thread.current
-
original, current[:available_queries_for_explain] = current[:available_queries_for_explain], false
-
yield
-
ensure
-
current[:available_queries_for_explain] = original
-
end
-
end
-
end
-
1
require 'active_support/notifications'
-
-
1
module ActiveRecord
-
1
class ExplainSubscriber # :nodoc:
-
1
def start(name, id, payload)
-
# unused
-
end
-
-
1
def finish(name, id, payload)
-
if queries = Thread.current[:available_queries_for_explain]
-
queries << payload.values_at(:sql, :binds) unless ignore_payload?(payload)
-
end
-
end
-
-
# SCHEMA queries cannot be EXPLAINed, also we do not want to run EXPLAIN on
-
# our own EXPLAINs now matter how loopingly beautiful that would be.
-
#
-
# On the other hand, we want to monitor the performance of our real database
-
# queries, not the performance of the access to the query cache.
-
1
IGNORED_PAYLOADS = %w(SCHEMA EXPLAIN CACHE)
-
1
EXPLAINED_SQLS = /\A\s*(select|update|delete|insert)/i
-
1
def ignore_payload?(payload)
-
payload[:exception] || IGNORED_PAYLOADS.include?(payload[:name]) || payload[:sql] !~ EXPLAINED_SQLS
-
end
-
-
1
ActiveSupport::Notifications.subscribe("sql.active_record", new)
-
end
-
end
-
1
module ActiveRecord
-
1
module Inheritance
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
# Determine whether to store the full constant name including namespace when using STI
-
1
class_attribute :store_full_sti_class, instance_writer: false
-
1
self.store_full_sti_class = true
-
end
-
-
1
module ClassMethods
-
# True if this isn't a concrete subclass needing a STI type condition.
-
1
def descends_from_active_record?
-
if self == Base
-
false
-
elsif superclass.abstract_class?
-
superclass.descends_from_active_record?
-
else
-
superclass == Base || !columns_hash.include?(inheritance_column)
-
end
-
end
-
-
1
def finder_needs_type_condition? #:nodoc:
-
# This is like this because benchmarking justifies the strange :false stuff
-
:true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true)
-
end
-
-
1
def symbolized_base_class
-
@symbolized_base_class ||= base_class.to_s.to_sym
-
end
-
-
1
def symbolized_sti_name
-
@symbolized_sti_name ||= sti_name.present? ? sti_name.to_sym : symbolized_base_class
-
end
-
-
# Returns the class descending directly from ActiveRecord::Base, or
-
# an abstract class, if any, in the inheritance hierarchy.
-
#
-
# If A extends AR::Base, A.base_class will return A. If B descends from A
-
# through some arbitrarily deep hierarchy, B.base_class will return A.
-
#
-
# If B < A and C < B and if A is an abstract_class then both B.base_class
-
# and C.base_class would return B as the answer since A is an abstract_class.
-
1
def base_class
-
unless self < Base
-
raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord"
-
end
-
-
if superclass == Base || superclass.abstract_class?
-
self
-
else
-
superclass.base_class
-
end
-
end
-
-
# Set this to true if this is an abstract class (see <tt>abstract_class?</tt>).
-
# If you are using inheritance with ActiveRecord and don't want child classes
-
# to utilize the implied STI table name of the parent class, this will need to be true.
-
# For example, given the following:
-
#
-
# class SuperClass < ActiveRecord::Base
-
# self.abstract_class = true
-
# end
-
# class Child < SuperClass
-
# self.table_name = 'the_table_i_really_want'
-
# end
-
#
-
#
-
# <tt>self.abstract_class = true</tt> is required to make <tt>Child<.find,.create, or any Arel method></tt> use <tt>the_table_i_really_want</tt> instead of a table called <tt>super_classes</tt>
-
#
-
1
attr_accessor :abstract_class
-
-
# Returns whether this class is an abstract class or not.
-
1
def abstract_class?
-
defined?(@abstract_class) && @abstract_class == true
-
end
-
-
1
def sti_name
-
store_full_sti_class ? name : name.demodulize
-
end
-
-
# Finder methods must instantiate through this method to work with the
-
# single-table inheritance model that makes it possible to create
-
# objects of different types from the same table.
-
1
def instantiate(record, column_types = {})
-
sti_class = find_sti_class(record[inheritance_column])
-
column_types = sti_class.decorate_columns(column_types)
-
sti_class.allocate.init_with('attributes' => record, 'column_types' => column_types)
-
end
-
-
1
protected
-
-
# Returns the class type of the record using the current module as a prefix. So descendants of
-
# MyApp::Business::Account would appear as MyApp::Business::AccountSubclass.
-
1
def compute_type(type_name)
-
if type_name.match(/^::/)
-
# If the type is prefixed with a scope operator then we assume that
-
# the type_name is an absolute reference.
-
ActiveSupport::Dependencies.constantize(type_name)
-
else
-
# Build a list of candidates to search for
-
candidates = []
-
name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" }
-
candidates << type_name
-
-
candidates.each do |candidate|
-
begin
-
constant = ActiveSupport::Dependencies.constantize(candidate)
-
return constant if candidate == constant.to_s
-
rescue NameError => e
-
# We don't want to swallow NoMethodError < NameError errors
-
raise e unless e.instance_of?(NameError)
-
end
-
end
-
-
raise NameError, "uninitialized constant #{candidates.first}"
-
end
-
end
-
-
1
private
-
-
1
def find_sti_class(type_name)
-
if type_name.blank? || !columns_hash.include?(inheritance_column)
-
self
-
else
-
begin
-
if store_full_sti_class
-
ActiveSupport::Dependencies.constantize(type_name)
-
else
-
compute_type(type_name)
-
end
-
rescue NameError
-
raise SubclassNotFound,
-
"The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. " +
-
"This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " +
-
"Please rename this column if you didn't intend it to be used for storing the inheritance class " +
-
"or overwrite #{name}.inheritance_column to use another column for that information."
-
end
-
end
-
end
-
-
1
def type_condition(table = arel_table)
-
sti_column = table[inheritance_column.to_sym]
-
sti_names = ([self] + descendants).map { |model| model.sti_name }
-
-
sti_column.in(sti_names)
-
end
-
end
-
-
1
private
-
-
# Sets the attribute used for single table inheritance to this class name if this is not the
-
# ActiveRecord::Base descendant.
-
# Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to
-
# do Reply.new without having to set <tt>Reply[Reply.inheritance_column] = "Reply"</tt> yourself.
-
# No such attribute would be set for objects of the Message class in that example.
-
1
def ensure_proper_type
-
klass = self.class
-
if klass.finder_needs_type_condition?
-
write_attribute(klass.inheritance_column, klass.sti_name)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Integration
-
# Returns a String, which Action Pack uses for constructing an URL to this
-
# object. The default implementation returns this record's id as a String,
-
# or nil if this record's unsaved.
-
#
-
# For example, suppose that you have a User model, and that you have a
-
# <tt>resources :users</tt> route. Normally, +user_path+ will
-
# construct a path with the user object's 'id' in it:
-
#
-
# user = User.find_by_name('Phusion')
-
# user_path(user) # => "/users/1"
-
#
-
# You can override +to_param+ in your model to make +user_path+ construct
-
# a path using the user's name instead of the user's id:
-
#
-
# class User < ActiveRecord::Base
-
# def to_param # overridden
-
# name
-
# end
-
# end
-
#
-
# user = User.find_by_name('Phusion')
-
# user_path(user) # => "/users/Phusion"
-
1
def to_param
-
# We can't use alias_method here, because method 'id' optimizes itself on the fly.
-
id && id.to_s # Be sure to stringify the id for routes
-
end
-
-
# Returns a cache key that can be used to identify this record.
-
#
-
# ==== Examples
-
#
-
# Product.new.cache_key # => "products/new"
-
# Product.find(5).cache_key # => "products/5" (updated_at not available)
-
# Person.find(5).cache_key # => "people/5-20071224150000" (updated_at available)
-
1
def cache_key
-
case
-
when new_record?
-
"#{self.class.model_name.cache_key}/new"
-
when timestamp = self[:updated_at]
-
timestamp = timestamp.utc.to_s(:nsec)
-
"#{self.class.model_name.cache_key}/#{id}-#{timestamp}"
-
else
-
"#{self.class.model_name.cache_key}/#{id}"
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Locking
-
# == What is Optimistic Locking
-
#
-
# Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of
-
# conflicts with the data. It does this by checking whether another process has made changes to a record since
-
# it was opened, an <tt>ActiveRecord::StaleObjectError</tt> exception is thrown if that has occurred
-
# and the update is ignored.
-
#
-
# Check out <tt>ActiveRecord::Locking::Pessimistic</tt> for an alternative.
-
#
-
# == Usage
-
#
-
# Active Records support optimistic locking if the field +lock_version+ is present. Each update to the
-
# record increments the +lock_version+ column and the locking facilities ensure that records instantiated twice
-
# will let the last one saved raise a +StaleObjectError+ if the first was also updated. Example:
-
#
-
# p1 = Person.find(1)
-
# p2 = Person.find(1)
-
#
-
# p1.first_name = "Michael"
-
# p1.save
-
#
-
# p2.first_name = "should fail"
-
# p2.save # Raises a ActiveRecord::StaleObjectError
-
#
-
# Optimistic locking will also check for stale data when objects are destroyed. Example:
-
#
-
# p1 = Person.find(1)
-
# p2 = Person.find(1)
-
#
-
# p1.first_name = "Michael"
-
# p1.save
-
#
-
# p2.destroy # Raises a ActiveRecord::StaleObjectError
-
#
-
# You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging,
-
# or otherwise apply the business logic needed to resolve the conflict.
-
#
-
# This locking mechanism will function inside a single Ruby process. To make it work across all
-
# web requests, the recommended approach is to add +lock_version+ as a hidden field to your form.
-
#
-
# This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>.
-
# To override the name of the +lock_version+ column, set the <tt>locking_column</tt> class attribute:
-
#
-
# class Person < ActiveRecord::Base
-
# self.locking_column = :lock_person
-
# end
-
#
-
1
module Optimistic
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :lock_optimistically, instance_writer: false
-
1
self.lock_optimistically = true
-
end
-
-
1
def locking_enabled? #:nodoc:
-
self.class.locking_enabled?
-
end
-
-
1
private
-
1
def increment_lock
-
lock_col = self.class.locking_column
-
previous_lock_value = send(lock_col).to_i
-
send(lock_col + '=', previous_lock_value + 1)
-
end
-
-
1
def update(attribute_names = @attributes.keys) #:nodoc:
-
return super unless locking_enabled?
-
return 0 if attribute_names.empty?
-
-
lock_col = self.class.locking_column
-
previous_lock_value = send(lock_col).to_i
-
increment_lock
-
-
attribute_names += [lock_col]
-
attribute_names.uniq!
-
-
begin
-
relation = self.class.unscoped
-
-
stmt = relation.where(
-
relation.table[self.class.primary_key].eq(id).and(
-
relation.table[lock_col].eq(self.class.quote_value(previous_lock_value))
-
)
-
).arel.compile_update(arel_attributes_with_values_for_update(attribute_names))
-
-
affected_rows = connection.update stmt
-
-
unless affected_rows == 1
-
raise ActiveRecord::StaleObjectError.new(self, "update")
-
end
-
-
affected_rows
-
-
# If something went wrong, revert the version.
-
rescue Exception
-
send(lock_col + '=', previous_lock_value)
-
raise
-
end
-
end
-
-
1
def destroy_row
-
affected_rows = super
-
-
if locking_enabled? && affected_rows != 1
-
raise ActiveRecord::StaleObjectError.new(self, "destroy")
-
end
-
-
affected_rows
-
end
-
-
1
def relation_for_destroy
-
relation = super
-
-
if locking_enabled?
-
column_name = self.class.locking_column
-
column = self.class.columns_hash[column_name]
-
substitute = connection.substitute_at(column, relation.bind_values.length)
-
-
relation = relation.where(self.class.arel_table[column_name].eq(substitute))
-
relation.bind_values << [column, self[column_name].to_i]
-
end
-
-
relation
-
end
-
-
1
module ClassMethods
-
1
DEFAULT_LOCKING_COLUMN = 'lock_version'
-
-
# Returns true if the +lock_optimistically+ flag is set to true
-
# (which it is, by default) and the table includes the
-
# +locking_column+ column (defaults to +lock_version+).
-
1
def locking_enabled?
-
lock_optimistically && columns_hash[locking_column]
-
end
-
-
# Set the column to use for optimistic locking. Defaults to +lock_version+.
-
1
def locking_column=(value)
-
@locking_column = value.to_s
-
end
-
-
# The version column used for optimistic locking. Defaults to +lock_version+.
-
1
def locking_column
-
reset_locking_column unless defined?(@locking_column)
-
@locking_column
-
end
-
-
# Quote the column name used for optimistic locking.
-
1
def quoted_locking_column
-
connection.quote_column_name(locking_column)
-
end
-
-
# Reset the column used for optimistic locking back to the +lock_version+ default.
-
1
def reset_locking_column
-
self.locking_column = DEFAULT_LOCKING_COLUMN
-
end
-
-
# Make sure the lock version column gets updated when counters are
-
# updated.
-
1
def update_counters(id, counters)
-
counters = counters.merge(locking_column => 1) if locking_enabled?
-
super
-
end
-
-
1
def column_defaults
-
@column_defaults ||= begin
-
defaults = super
-
-
if defaults.key?(locking_column) && lock_optimistically
-
defaults[locking_column] ||= 0
-
end
-
-
defaults
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Locking
-
# Locking::Pessimistic provides support for row-level locking using
-
# SELECT ... FOR UPDATE and other lock types.
-
#
-
# Pass <tt>:lock => true</tt> to <tt>ActiveRecord::Base.find</tt> to obtain an exclusive
-
# lock on the selected rows:
-
# # select * from accounts where id=1 for update
-
# Account.find(1, :lock => true)
-
#
-
# Pass <tt>:lock => 'some locking clause'</tt> to give a database-specific locking clause
-
# of your own such as 'LOCK IN SHARE MODE' or 'FOR UPDATE NOWAIT'. Example:
-
#
-
# Account.transaction do
-
# # select * from accounts where name = 'shugo' limit 1 for update
-
# shugo = Account.where("name = 'shugo'").lock(true).first
-
# yuko = Account.where("name = 'yuko'").lock(true).first
-
# shugo.balance -= 100
-
# shugo.save!
-
# yuko.balance += 100
-
# yuko.save!
-
# end
-
#
-
# You can also use <tt>ActiveRecord::Base#lock!</tt> method to lock one record by id.
-
# This may be better if you don't need to lock every row. Example:
-
#
-
# Account.transaction do
-
# # select * from accounts where ...
-
# accounts = Account.where(...).all
-
# account1 = accounts.detect { |account| ... }
-
# account2 = accounts.detect { |account| ... }
-
# # select * from accounts where id=? for update
-
# account1.lock!
-
# account2.lock!
-
# account1.balance -= 100
-
# account1.save!
-
# account2.balance += 100
-
# account2.save!
-
# end
-
#
-
# You can start a transaction and acquire the lock in one go by calling
-
# <tt>with_lock</tt> with a block. The block is called from within
-
# a transaction, the object is already locked. Example:
-
#
-
# account = Account.first
-
# account.with_lock do
-
# # This block is called within a transaction,
-
# # account is already locked.
-
# account.balance -= 100
-
# account.save!
-
# end
-
#
-
# Database-specific information on row locking:
-
# MySQL: http://dev.mysql.com/doc/refman/5.1/en/innodb-locking-reads.html
-
# PostgreSQL: http://www.postgresql.org/docs/current/interactive/sql-select.html#SQL-FOR-UPDATE-SHARE
-
1
module Pessimistic
-
# Obtain a row lock on this record. Reloads the record to obtain the requested
-
# lock. Pass an SQL locking clause to append the end of the SELECT statement
-
# or pass true for "FOR UPDATE" (the default, an exclusive row lock). Returns
-
# the locked record.
-
1
def lock!(lock = true)
-
reload(:lock => lock) if persisted?
-
self
-
end
-
-
# Wraps the passed block in a transaction, locking the object
-
# before yielding. You pass can the SQL locking clause
-
# as argument (see <tt>lock!</tt>).
-
1
def with_lock(lock = true)
-
transaction do
-
lock!(lock)
-
yield
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
class LogSubscriber < ActiveSupport::LogSubscriber
-
1
IGNORE_PAYLOAD_NAMES = ["SCHEMA", "EXPLAIN"]
-
-
1
def self.runtime=(value)
-
Thread.current[:active_record_sql_runtime] = value
-
end
-
-
1
def self.runtime
-
Thread.current[:active_record_sql_runtime] ||= 0
-
end
-
-
1
def self.reset_runtime
-
rt, self.runtime = runtime, 0
-
rt
-
end
-
-
1
def initialize
-
1
super
-
1
@odd_or_even = false
-
end
-
-
1
def sql(event)
-
self.class.runtime += event.duration
-
return unless logger.debug?
-
-
payload = event.payload
-
-
return if IGNORE_PAYLOAD_NAMES.include?(payload[:name])
-
-
name = "#{payload[:name]} (#{event.duration.round(1)}ms)"
-
sql = payload[:sql].squeeze(' ')
-
binds = nil
-
-
unless (payload[:binds] || []).empty?
-
binds = " " + payload[:binds].map { |col,v|
-
[col.name, v]
-
}.inspect
-
end
-
-
if odd?
-
name = color(name, CYAN, true)
-
sql = color(sql, nil, true)
-
else
-
name = color(name, MAGENTA, true)
-
end
-
-
debug " #{name} #{sql}#{binds}"
-
end
-
-
1
def identity(event)
-
return unless logger.debug?
-
-
name = color(event.payload[:name], odd? ? CYAN : MAGENTA, true)
-
line = odd? ? color(event.payload[:line], nil, true) : event.payload[:line]
-
-
debug " #{name} #{line}"
-
end
-
-
1
def odd?
-
@odd_or_even = !@odd_or_even
-
end
-
-
1
def logger
-
ActiveRecord::Base.logger
-
end
-
end
-
end
-
-
1
ActiveRecord::LogSubscriber.attach_to :active_record
-
1
require "active_support/core_ext/class/attribute_accessors"
-
1
require 'set'
-
-
1
module ActiveRecord
-
# Exception that can be raised to stop migrations from going backwards.
-
1
class IrreversibleMigration < ActiveRecordError
-
end
-
-
1
class DuplicateMigrationVersionError < ActiveRecordError#:nodoc:
-
1
def initialize(version)
-
super("Multiple migrations have the version number #{version}")
-
end
-
end
-
-
1
class DuplicateMigrationNameError < ActiveRecordError#:nodoc:
-
1
def initialize(name)
-
super("Multiple migrations have the name #{name}")
-
end
-
end
-
-
1
class UnknownMigrationVersionError < ActiveRecordError #:nodoc:
-
1
def initialize(version)
-
super("No migration with version number #{version}")
-
end
-
end
-
-
1
class IllegalMigrationNameError < ActiveRecordError#:nodoc:
-
1
def initialize(name)
-
super("Illegal name for migration file: #{name}\n\t(only lower case letters, numbers, and '_' allowed)")
-
end
-
end
-
-
1
class PendingMigrationError < ActiveRecordError#:nodoc:
-
1
def initialize
-
super("Migrations are pending; run 'rake db:migrate RAILS_ENV=#{ENV['RAILS_ENV']}' to resolve this issue.")
-
end
-
end
-
-
# = Active Record Migrations
-
#
-
# Migrations can manage the evolution of a schema used by several physical
-
# databases. It's a solution to the common problem of adding a field to make
-
# a new feature work in your local database, but being unsure of how to
-
# push that change to other developers and to the production server. With
-
# migrations, you can describe the transformations in self-contained classes
-
# that can be checked into version control systems and executed against
-
# another database that might be one, two, or five versions behind.
-
#
-
# Example of a simple migration:
-
#
-
# class AddSsl < ActiveRecord::Migration
-
# def up
-
# add_column :accounts, :ssl_enabled, :boolean, default: true
-
# end
-
#
-
# def down
-
# remove_column :accounts, :ssl_enabled
-
# end
-
# end
-
#
-
# This migration will add a boolean flag to the accounts table and remove it
-
# if you're backing out of the migration. It shows how all migrations have
-
# two methods +up+ and +down+ that describes the transformations
-
# required to implement or remove the migration. These methods can consist
-
# of both the migration specific methods like +add_column+ and +remove_column+,
-
# but may also contain regular Ruby code for generating data needed for the
-
# transformations.
-
#
-
# Example of a more complex migration that also needs to initialize data:
-
#
-
# class AddSystemSettings < ActiveRecord::Migration
-
# def up
-
# create_table :system_settings do |t|
-
# t.string :name
-
# t.string :label
-
# t.text :value
-
# t.string :type
-
# t.integer :position
-
# end
-
#
-
# SystemSetting.create name: 'notice',
-
# label: 'Use notice?',
-
# value: 1
-
# end
-
#
-
# def down
-
# drop_table :system_settings
-
# end
-
# end
-
#
-
# This migration first adds the +system_settings+ table, then creates the very
-
# first row in it using the Active Record model that relies on the table. It
-
# also uses the more advanced +create_table+ syntax where you can specify a
-
# complete table schema in one block call.
-
#
-
# == Available transformations
-
#
-
# * <tt>create_table(name, options)</tt>: Creates a table called +name+ and
-
# makes the table object available to a block that can then add columns to it,
-
# following the same format as +add_column+. See example above. The options hash
-
# is for fragments like "DEFAULT CHARSET=UTF-8" that are appended to the create
-
# table definition.
-
# * <tt>drop_table(name)</tt>: Drops the table called +name+.
-
# * <tt>change_table(name, options)</tt>: Allows to make column alterations to
-
# the table called +name+. It makes the table object availabe to a block that
-
# can then add/remove columns, indexes or foreign keys to it.
-
# * <tt>rename_table(old_name, new_name)</tt>: Renames the table called +old_name+
-
# to +new_name+.
-
# * <tt>add_column(table_name, column_name, type, options)</tt>: Adds a new column
-
# to the table called +table_name+
-
# named +column_name+ specified to be one of the following types:
-
# <tt>:string</tt>, <tt>:text</tt>, <tt>:integer</tt>, <tt>:float</tt>,
-
# <tt>:decimal</tt>, <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>,
-
# <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>. A default value can be
-
# specified by passing an +options+ hash like <tt>{ default: 11 }</tt>.
-
# Other options include <tt>:limit</tt> and <tt>:null</tt> (e.g.
-
# <tt>{ limit: 50, null: false }</tt>) -- see
-
# ActiveRecord::ConnectionAdapters::TableDefinition#column for details.
-
# * <tt>rename_column(table_name, column_name, new_column_name)</tt>: Renames
-
# a column but keeps the type and content.
-
# * <tt>change_column(table_name, column_name, type, options)</tt>: Changes
-
# the column to a different type using the same parameters as add_column.
-
# * <tt>remove_column(table_name, column_names)</tt>: Removes the column listed in
-
# +column_names+ from the table called +table_name+.
-
# * <tt>add_index(table_name, column_names, options)</tt>: Adds a new index
-
# with the name of the column. Other options include
-
# <tt>:name</tt>, <tt>:unique</tt> (e.g.
-
# <tt>{ name: 'users_name_index', unique: true }</tt>) and <tt>:order</tt>
-
# (e.g. <tt>{ order: { name: :desc } }</tt>).
-
# * <tt>remove_index(table_name, column: column_name)</tt>: Removes the index
-
# specified by +column_name+.
-
# * <tt>remove_index(table_name, name: index_name)</tt>: Removes the index
-
# specified by +index_name+.
-
#
-
# == Irreversible transformations
-
#
-
# Some transformations are destructive in a manner that cannot be reversed.
-
# Migrations of that kind should raise an <tt>ActiveRecord::IrreversibleMigration</tt>
-
# exception in their +down+ method.
-
#
-
# == Running migrations from within Rails
-
#
-
# The Rails package has several tools to help create and apply migrations.
-
#
-
# To generate a new migration, you can use
-
# rails generate migration MyNewMigration
-
#
-
# where MyNewMigration is the name of your migration. The generator will
-
# create an empty migration file <tt>timestamp_my_new_migration.rb</tt>
-
# in the <tt>db/migrate/</tt> directory where <tt>timestamp</tt> is the
-
# UTC formatted date and time that the migration was generated.
-
#
-
# You may then edit the <tt>up</tt> and <tt>down</tt> methods of
-
# MyNewMigration.
-
#
-
# There is a special syntactic shortcut to generate migrations that add fields to a table.
-
#
-
# rails generate migration add_fieldname_to_tablename fieldname:string
-
#
-
# This will generate the file <tt>timestamp_add_fieldname_to_tablename</tt>, which will look like this:
-
# class AddFieldnameToTablename < ActiveRecord::Migration
-
# def up
-
# add_column :tablenames, :fieldname, :string
-
# end
-
#
-
# def down
-
# remove_column :tablenames, :fieldname
-
# end
-
# end
-
#
-
# To run migrations against the currently configured database, use
-
# <tt>rake db:migrate</tt>. This will update the database by running all of the
-
# pending migrations, creating the <tt>schema_migrations</tt> table
-
# (see "About the schema_migrations table" section below) if missing. It will also
-
# invoke the db:schema:dump task, which will update your db/schema.rb file
-
# to match the structure of your database.
-
#
-
# To roll the database back to a previous migration version, use
-
# <tt>rake db:migrate VERSION=X</tt> where <tt>X</tt> is the version to which
-
# you wish to downgrade. If any of the migrations throw an
-
# <tt>ActiveRecord::IrreversibleMigration</tt> exception, that step will fail and you'll
-
# have some manual work to do.
-
#
-
# == Database support
-
#
-
# Migrations are currently supported in MySQL, PostgreSQL, SQLite,
-
# SQL Server, Sybase, and Oracle (all supported databases except DB2).
-
#
-
# == More examples
-
#
-
# Not all migrations change the schema. Some just fix the data:
-
#
-
# class RemoveEmptyTags < ActiveRecord::Migration
-
# def up
-
# Tag.all.each { |tag| tag.destroy if tag.pages.empty? }
-
# end
-
#
-
# def down
-
# # not much we can do to restore deleted data
-
# raise ActiveRecord::IrreversibleMigration, "Can't recover the deleted tags"
-
# end
-
# end
-
#
-
# Others remove columns when they migrate up instead of down:
-
#
-
# class RemoveUnnecessaryItemAttributes < ActiveRecord::Migration
-
# def up
-
# remove_column :items, :incomplete_items_count
-
# remove_column :items, :completed_items_count
-
# end
-
#
-
# def down
-
# add_column :items, :incomplete_items_count
-
# add_column :items, :completed_items_count
-
# end
-
# end
-
#
-
# And sometimes you need to do something in SQL not abstracted directly by migrations:
-
#
-
# class MakeJoinUnique < ActiveRecord::Migration
-
# def up
-
# execute "ALTER TABLE `pages_linked_pages` ADD UNIQUE `page_id_linked_page_id` (`page_id`,`linked_page_id`)"
-
# end
-
#
-
# def down
-
# execute "ALTER TABLE `pages_linked_pages` DROP INDEX `page_id_linked_page_id`"
-
# end
-
# end
-
#
-
# == Using a model after changing its table
-
#
-
# Sometimes you'll want to add a column in a migration and populate it
-
# immediately after. In that case, you'll need to make a call to
-
# <tt>Base#reset_column_information</tt> in order to ensure that the model has the
-
# latest column data from after the new column was added. Example:
-
#
-
# class AddPeopleSalary < ActiveRecord::Migration
-
# def up
-
# add_column :people, :salary, :integer
-
# Person.reset_column_information
-
# Person.all.each do |p|
-
# p.update_attribute :salary, SalaryCalculator.compute(p)
-
# end
-
# end
-
# end
-
#
-
# == Controlling verbosity
-
#
-
# By default, migrations will describe the actions they are taking, writing
-
# them to the console as they happen, along with benchmarks describing how
-
# long each step took.
-
#
-
# You can quiet them down by setting ActiveRecord::Migration.verbose = false.
-
#
-
# You can also insert your own messages and benchmarks by using the +say_with_time+
-
# method:
-
#
-
# def up
-
# ...
-
# say_with_time "Updating salaries..." do
-
# Person.all.each do |p|
-
# p.update_attribute :salary, SalaryCalculator.compute(p)
-
# end
-
# end
-
# ...
-
# end
-
#
-
# The phrase "Updating salaries..." would then be printed, along with the
-
# benchmark for the block when the block completes.
-
#
-
# == About the schema_migrations table
-
#
-
# Rails versions 2.0 and prior used to create a table called
-
# <tt>schema_info</tt> when using migrations. This table contained the
-
# version of the schema as of the last applied migration.
-
#
-
# Starting with Rails 2.1, the <tt>schema_info</tt> table is
-
# (automatically) replaced by the <tt>schema_migrations</tt> table, which
-
# contains the version numbers of all the migrations applied.
-
#
-
# As a result, it is now possible to add migration files that are numbered
-
# lower than the current schema version: when migrating up, those
-
# never-applied "interleaved" migrations will be automatically applied, and
-
# when migrating down, never-applied "interleaved" migrations will be skipped.
-
#
-
# == Timestamped Migrations
-
#
-
# By default, Rails generates migrations that look like:
-
#
-
# 20080717013526_your_migration_name.rb
-
#
-
# The prefix is a generation timestamp (in UTC).
-
#
-
# If you'd prefer to use numeric prefixes, you can turn timestamped migrations
-
# off by setting:
-
#
-
# config.active_record.timestamped_migrations = false
-
#
-
# In application.rb.
-
#
-
# == Reversible Migrations
-
#
-
# Starting with Rails 3.1, you will be able to define reversible migrations.
-
# Reversible migrations are migrations that know how to go +down+ for you.
-
# You simply supply the +up+ logic, and the Migration system will figure out
-
# how to execute the down commands for you.
-
#
-
# To define a reversible migration, define the +change+ method in your
-
# migration like this:
-
#
-
# class TenderloveMigration < ActiveRecord::Migration
-
# def change
-
# create_table(:horses) do |t|
-
# t.column :content, :text
-
# t.column :remind_at, :datetime
-
# end
-
# end
-
# end
-
#
-
# This migration will create the horses table for you on the way up, and
-
# automatically figure out how to drop the table on the way down.
-
#
-
# Some commands like +remove_column+ cannot be reversed. If you care to
-
# define how to move up and down in these cases, you should define the +up+
-
# and +down+ methods as before.
-
#
-
# If a command cannot be reversed, an
-
# <tt>ActiveRecord::IrreversibleMigration</tt> exception will be raised when
-
# the migration is moving down.
-
#
-
# For a list of commands that are reversible, please see
-
# <tt>ActiveRecord::Migration::CommandRecorder</tt>.
-
1
class Migration
-
1
autoload :CommandRecorder, 'active_record/migration/command_recorder'
-
-
-
# This class is used to verify that all migrations have been run before
-
# loading a web page if config.active_record.migration_error is set to :page_load
-
1
class CheckPending
-
1
def initialize(app)
-
@app = app
-
end
-
-
1
def call(env)
-
ActiveRecord::Base.logger.quietly do
-
ActiveRecord::Migration.check_pending!
-
end
-
@app.call(env)
-
end
-
end
-
-
1
class << self
-
1
attr_accessor :delegate # :nodoc:
-
end
-
-
1
def self.check_pending!
-
raise ActiveRecord::PendingMigrationError if ActiveRecord::Migrator.needs_migration?
-
end
-
-
1
def self.method_missing(name, *args, &block) # :nodoc:
-
(delegate || superclass.delegate).send(name, *args, &block)
-
end
-
-
1
def self.migrate(direction)
-
new.migrate direction
-
end
-
-
1
cattr_accessor :verbose
-
-
1
attr_accessor :name, :version
-
-
1
def initialize(name = self.class.name, version = nil)
-
1
@name = name
-
1
@version = version
-
1
@connection = nil
-
1
@reverting = false
-
end
-
-
# instantiate the delegate object after initialize is defined
-
1
self.verbose = true
-
1
self.delegate = new
-
-
1
def revert
-
@reverting = true
-
yield
-
ensure
-
@reverting = false
-
end
-
-
1
def reverting?
-
@reverting
-
end
-
-
1
def up
-
self.class.delegate = self
-
return unless self.class.respond_to?(:up)
-
self.class.up
-
end
-
-
1
def down
-
self.class.delegate = self
-
return unless self.class.respond_to?(:down)
-
self.class.down
-
end
-
-
# Execute this migration in the named direction
-
1
def migrate(direction)
-
return unless respond_to?(direction)
-
-
case direction
-
when :up then announce "migrating"
-
when :down then announce "reverting"
-
end
-
-
time = nil
-
ActiveRecord::Base.connection_pool.with_connection do |conn|
-
@connection = conn
-
if respond_to?(:change)
-
if direction == :down
-
recorder = CommandRecorder.new(@connection)
-
suppress_messages do
-
@connection = recorder
-
change
-
end
-
@connection = conn
-
time = Benchmark.measure {
-
self.revert {
-
recorder.inverse.each do |cmd, args|
-
send(cmd, *args)
-
end
-
}
-
}
-
else
-
time = Benchmark.measure { change }
-
end
-
else
-
time = Benchmark.measure { send(direction) }
-
end
-
@connection = nil
-
end
-
-
case direction
-
when :up then announce "migrated (%.4fs)" % time.real; write
-
when :down then announce "reverted (%.4fs)" % time.real; write
-
end
-
end
-
-
1
def write(text="")
-
puts(text) if verbose
-
end
-
-
1
def announce(message)
-
text = "#{version} #{name}: #{message}"
-
length = [0, 75 - text.length].max
-
write "== %s %s" % [text, "=" * length]
-
end
-
-
1
def say(message, subitem=false)
-
write "#{subitem ? " ->" : "--"} #{message}"
-
end
-
-
1
def say_with_time(message)
-
say(message)
-
result = nil
-
time = Benchmark.measure { result = yield }
-
say "%.4fs" % time.real, :subitem
-
say("#{result} rows", :subitem) if result.is_a?(Integer)
-
result
-
end
-
-
1
def suppress_messages
-
save, self.verbose = verbose, false
-
yield
-
ensure
-
self.verbose = save
-
end
-
-
1
def connection
-
@connection || ActiveRecord::Base.connection
-
end
-
-
1
def method_missing(method, *arguments, &block)
-
arg_list = arguments.map{ |a| a.inspect } * ', '
-
-
say_with_time "#{method}(#{arg_list})" do
-
unless reverting?
-
unless arguments.empty? || method == :execute
-
arguments[0] = Migrator.proper_table_name(arguments.first)
-
arguments[1] = Migrator.proper_table_name(arguments.second) if method == :rename_table
-
end
-
end
-
return super unless connection.respond_to?(method)
-
connection.send(method, *arguments, &block)
-
end
-
end
-
-
1
def copy(destination, sources, options = {})
-
copied = []
-
-
FileUtils.mkdir_p(destination) unless File.exists?(destination)
-
-
destination_migrations = ActiveRecord::Migrator.migrations(destination)
-
last = destination_migrations.last
-
sources.each do |scope, path|
-
source_migrations = ActiveRecord::Migrator.migrations(path)
-
-
source_migrations.each do |migration|
-
source = File.read(migration.filename)
-
source = "# This migration comes from #{scope} (originally #{migration.version})\n#{source}"
-
-
if duplicate = destination_migrations.detect { |m| m.name == migration.name }
-
if options[:on_skip] && duplicate.scope != scope.to_s
-
options[:on_skip].call(scope, migration)
-
end
-
next
-
end
-
-
migration.version = next_migration_number(last ? last.version + 1 : 0).to_i
-
new_path = File.join(destination, "#{migration.version}_#{migration.name.underscore}.#{scope}.rb")
-
old_path, migration.filename = migration.filename, new_path
-
last = migration
-
-
File.open(migration.filename, "w") { |f| f.write source }
-
copied << migration
-
options[:on_copy].call(scope, migration, old_path) if options[:on_copy]
-
destination_migrations << migration
-
end
-
end
-
-
copied
-
end
-
-
1
def next_migration_number(number)
-
if ActiveRecord::Base.timestamped_migrations
-
[Time.now.utc.strftime("%Y%m%d%H%M%S"), "%.14d" % number].max
-
else
-
"%.3d" % number
-
end
-
end
-
end
-
-
# MigrationProxy is used to defer loading of the actual migration classes
-
# until they are needed
-
1
class MigrationProxy < Struct.new(:name, :version, :filename, :scope)
-
-
1
def initialize(name, version, filename, scope)
-
super
-
@migration = nil
-
end
-
-
1
def basename
-
File.basename(filename)
-
end
-
-
1
delegate :migrate, :announce, :write, :to => :migration
-
-
1
private
-
-
1
def migration
-
@migration ||= load_migration
-
end
-
-
1
def load_migration
-
require(File.expand_path(filename))
-
name.constantize.new
-
end
-
-
end
-
-
1
class Migrator#:nodoc:
-
1
class << self
-
1
attr_writer :migrations_paths
-
1
alias :migrations_path= :migrations_paths=
-
-
1
def migrate(migrations_paths, target_version = nil, &block)
-
case
-
when target_version.nil?
-
up(migrations_paths, target_version, &block)
-
when current_version == 0 && target_version == 0
-
[]
-
when current_version > target_version
-
down(migrations_paths, target_version, &block)
-
else
-
up(migrations_paths, target_version, &block)
-
end
-
end
-
-
1
def rollback(migrations_paths, steps=1)
-
move(:down, migrations_paths, steps)
-
end
-
-
1
def forward(migrations_paths, steps=1)
-
move(:up, migrations_paths, steps)
-
end
-
-
1
def up(migrations_paths, target_version = nil)
-
migrations = migrations(migrations_paths)
-
migrations.select! { |m| yield m } if block_given?
-
-
self.new(:up, migrations, target_version).migrate
-
end
-
-
1
def down(migrations_paths, target_version = nil, &block)
-
migrations = migrations(migrations_paths)
-
migrations.select! { |m| yield m } if block_given?
-
-
self.new(:down, migrations, target_version).migrate
-
end
-
-
1
def run(direction, migrations_paths, target_version)
-
self.new(direction, migrations(migrations_paths), target_version).run
-
end
-
-
1
def open(migrations_paths)
-
self.new(:up, migrations(migrations_paths), nil)
-
end
-
-
1
def schema_migrations_table_name
-
SchemaMigration.table_name
-
end
-
-
1
def get_all_versions
-
SchemaMigration.all.map { |x| x.version.to_i }.sort
-
end
-
-
1
def current_version
-
sm_table = schema_migrations_table_name
-
if Base.connection.table_exists?(sm_table)
-
get_all_versions.max || 0
-
else
-
0
-
end
-
end
-
-
1
def needs_migration?
-
current_version < last_version
-
end
-
-
1
def last_version
-
migrations(migrations_paths).last.try(:version)||0
-
end
-
-
1
def proper_table_name(name)
-
# Use the Active Record objects own table_name, or pre/suffix from ActiveRecord::Base if name is a symbol/string
-
if name.respond_to? :table_name
-
name.table_name
-
else
-
"#{ActiveRecord::Base.table_name_prefix}#{name}#{ActiveRecord::Base.table_name_suffix}"
-
end
-
end
-
-
1
def migrations_paths
-
@migrations_paths ||= ['db/migrate']
-
# just to not break things if someone uses: migration_path = some_string
-
Array(@migrations_paths)
-
end
-
-
1
def migrations_path
-
migrations_paths.first
-
end
-
-
1
def migrations(paths)
-
paths = Array(paths)
-
-
files = Dir[*paths.map { |p| "#{p}/**/[0-9]*_*.rb" }]
-
-
migrations = files.map do |file|
-
version, name, scope = file.scan(/([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?.rb/).first
-
-
raise IllegalMigrationNameError.new(file) unless version
-
version = version.to_i
-
name = name.camelize
-
-
MigrationProxy.new(name, version, file, scope)
-
end
-
-
migrations.sort_by(&:version)
-
end
-
-
1
private
-
-
1
def move(direction, migrations_paths, steps)
-
migrator = self.new(direction, migrations(migrations_paths))
-
start_index = migrator.migrations.index(migrator.current_migration)
-
-
if start_index
-
finish = migrator.migrations[start_index + steps]
-
version = finish ? finish.version : 0
-
send(direction, migrations_paths, version)
-
end
-
end
-
end
-
-
1
def initialize(direction, migrations, target_version = nil)
-
raise StandardError.new("This database does not yet support migrations") unless Base.connection.supports_migrations?
-
-
@direction = direction
-
@target_version = target_version
-
@migrated_versions = nil
-
-
if Array(migrations).grep(String).empty?
-
@migrations = migrations
-
else
-
ActiveSupport::Deprecation.warn "instantiate this class with a list of migrations"
-
@migrations = self.class.migrations(migrations)
-
end
-
-
validate(@migrations)
-
-
ActiveRecord::SchemaMigration.create_table
-
end
-
-
1
def current_version
-
migrated.sort.last || 0
-
end
-
-
1
def current_migration
-
migrations.detect { |m| m.version == current_version }
-
end
-
1
alias :current :current_migration
-
-
1
def run
-
target = migrations.detect { |m| m.version == @target_version }
-
raise UnknownMigrationVersionError.new(@target_version) if target.nil?
-
unless (up? && migrated.include?(target.version.to_i)) || (down? && !migrated.include?(target.version.to_i))
-
target.migrate(@direction)
-
record_version_state_after_migrating(target.version)
-
end
-
end
-
-
1
def migrate
-
if !target && @target_version && @target_version > 0
-
raise UnknownMigrationVersionError.new(@target_version)
-
end
-
-
running = runnable
-
-
if block_given?
-
message = "block argument to migrate is deprecated, please filter migrations before constructing the migrator"
-
ActiveSupport::Deprecation.warn message
-
running.select! { |m| yield m }
-
end
-
-
running.each do |migration|
-
Base.logger.info "Migrating to #{migration.name} (#{migration.version})" if Base.logger
-
-
begin
-
ddl_transaction do
-
migration.migrate(@direction)
-
record_version_state_after_migrating(migration.version)
-
end
-
rescue => e
-
canceled_msg = Base.connection.supports_ddl_transactions? ? "this and " : ""
-
raise StandardError, "An error has occurred, #{canceled_msg}all later migrations canceled:\n\n#{e}", e.backtrace
-
end
-
end
-
end
-
-
1
def runnable
-
runnable = migrations[start..finish]
-
if up?
-
runnable.reject { |m| ran?(m) }
-
else
-
# skip the last migration if we're headed down, but not ALL the way down
-
runnable.pop if target
-
runnable.find_all { |m| ran?(m) }
-
end
-
end
-
-
1
def migrations
-
down? ? @migrations.reverse : @migrations.sort_by(&:version)
-
end
-
-
1
def pending_migrations
-
already_migrated = migrated
-
migrations.reject { |m| already_migrated.include?(m.version) }
-
end
-
-
1
def migrated
-
@migrated_versions ||= Set.new(self.class.get_all_versions)
-
end
-
-
1
private
-
1
def ran?(migration)
-
migrated.include?(migration.version.to_i)
-
end
-
-
1
def target
-
migrations.detect { |m| m.version == @target_version }
-
end
-
-
1
def finish
-
migrations.index(target) || migrations.size - 1
-
end
-
-
1
def start
-
up? ? 0 : (migrations.index(current) || 0)
-
end
-
-
1
def validate(migrations)
-
name ,= migrations.group_by(&:name).find { |_,v| v.length > 1 }
-
raise DuplicateMigrationNameError.new(name) if name
-
-
version ,= migrations.group_by(&:version).find { |_,v| v.length > 1 }
-
raise DuplicateMigrationVersionError.new(version) if version
-
end
-
-
1
def record_version_state_after_migrating(version)
-
if down?
-
migrated.delete(version)
-
ActiveRecord::SchemaMigration.where(:version => version.to_s).delete_all
-
else
-
migrated << version
-
ActiveRecord::SchemaMigration.create!(:version => version.to_s)
-
end
-
end
-
-
1
def up?
-
@direction == :up
-
end
-
-
1
def down?
-
@direction == :down
-
end
-
-
# Wrap the migration in a transaction only if supported by the adapter.
-
1
def ddl_transaction
-
if Base.connection.supports_ddl_transactions?
-
Base.transaction { yield }
-
else
-
yield
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
class Migration
-
1
module JoinTable #:nodoc:
-
1
private
-
-
1
def find_join_table_name(table_1, table_2, options = {})
-
options.delete(:table_name) || join_table_name(table_1, table_2)
-
end
-
-
1
def join_table_name(table_1, table_2)
-
[table_1, table_2].sort.join("_").to_sym
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module ModelSchema
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
##
-
# :singleton-method:
-
# Accessor for the prefix type that will be prepended to every primary key column name.
-
# The options are :table_name and :table_name_with_underscore. If the first is specified,
-
# the Product class will look for "productid" instead of "id" as the primary column. If the
-
# latter is specified, the Product class will look for "product_id" instead of "id". Remember
-
# that this is a global setting for all Active Records.
-
1
mattr_accessor :primary_key_prefix_type, instance_writer: false
-
-
##
-
# :singleton-method:
-
# Accessor for the name of the prefix string to prepend to every table name. So if set
-
# to "basecamp_", all table names will be named like "basecamp_projects", "basecamp_people",
-
# etc. This is a convenient way of creating a namespace for tables in a shared database.
-
# By default, the prefix is the empty string.
-
#
-
# If you are organising your models within modules you can add a prefix to the models within
-
# a namespace by defining a singleton method in the parent module called table_name_prefix which
-
# returns your chosen prefix.
-
1
class_attribute :table_name_prefix, instance_writer: false
-
1
self.table_name_prefix = ""
-
-
##
-
# :singleton-method:
-
# Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp",
-
# "people_basecamp"). By default, the suffix is the empty string.
-
1
class_attribute :table_name_suffix, instance_writer: false
-
1
self.table_name_suffix = ""
-
-
##
-
# :singleton-method:
-
# Indicates whether table names should be the pluralized versions of the corresponding class names.
-
# If true, the default table name for a Product class will be +products+. If false, it would just be +product+.
-
# See table_name for the full rules on table/class naming. This is true, by default.
-
1
class_attribute :pluralize_table_names, instance_writer: false
-
1
self.pluralize_table_names = true
-
-
1
self.inheritance_column = 'type'
-
end
-
-
1
module ClassMethods
-
# Guesses the table name (in forced lower-case) based on the name of the class in the
-
# inheritance hierarchy descending directly from ActiveRecord::Base. So if the hierarchy
-
# looks like: Reply < Message < ActiveRecord::Base, then Message is used
-
# to guess the table name even when called on Reply. The rules used to do the guess
-
# are handled by the Inflector class in Active Support, which knows almost all common
-
# English inflections. You can add new inflections in config/initializers/inflections.rb.
-
#
-
# Nested classes are given table names prefixed by the singular form of
-
# the parent's table name. Enclosing modules are not considered.
-
#
-
# ==== Examples
-
#
-
# class Invoice < ActiveRecord::Base
-
# end
-
#
-
# file class table_name
-
# invoice.rb Invoice invoices
-
#
-
# class Invoice < ActiveRecord::Base
-
# class Lineitem < ActiveRecord::Base
-
# end
-
# end
-
#
-
# file class table_name
-
# invoice.rb Invoice::Lineitem invoice_lineitems
-
#
-
# module Invoice
-
# class Lineitem < ActiveRecord::Base
-
# end
-
# end
-
#
-
# file class table_name
-
# invoice/lineitem.rb Invoice::Lineitem lineitems
-
#
-
# Additionally, the class-level +table_name_prefix+ is prepended and the
-
# +table_name_suffix+ is appended. So if you have "myapp_" as a prefix,
-
# the table name guess for an Invoice class becomes "myapp_invoices".
-
# Invoice::Lineitem becomes "myapp_invoice_lineitems".
-
#
-
# You can also set your own table name explicitly:
-
#
-
# class Mouse < ActiveRecord::Base
-
# self.table_name = "mice"
-
# end
-
#
-
# Alternatively, you can override the table_name method to define your
-
# own computation. (Possibly using <tt>super</tt> to manipulate the default
-
# table name.) Example:
-
#
-
# class Post < ActiveRecord::Base
-
# def self.table_name
-
# "special_" + super
-
# end
-
# end
-
# Post.table_name # => "special_posts"
-
1
def table_name
-
reset_table_name unless defined?(@table_name)
-
@table_name
-
end
-
-
# Sets the table name explicitly. Example:
-
#
-
# class Project < ActiveRecord::Base
-
# self.table_name = "project"
-
# end
-
#
-
# You can also just define your own <tt>self.table_name</tt> method; see
-
# the documentation for ActiveRecord::Base#table_name.
-
1
def table_name=(value)
-
value = value && value.to_s
-
-
if defined?(@table_name)
-
return if value == @table_name
-
reset_column_information if connected?
-
end
-
-
@table_name = value
-
@quoted_table_name = nil
-
@arel_table = nil
-
@sequence_name = nil unless defined?(@explicit_sequence_name) && @explicit_sequence_name
-
@relation = Relation.new(self, arel_table)
-
end
-
-
# Returns a quoted version of the table name, used to construct SQL statements.
-
1
def quoted_table_name
-
@quoted_table_name ||= connection.quote_table_name(table_name)
-
end
-
-
# Computes the table name, (re)sets it internally, and returns it.
-
1
def reset_table_name #:nodoc:
-
self.table_name = if abstract_class?
-
superclass == Base ? nil : superclass.table_name
-
elsif superclass.abstract_class?
-
superclass.table_name || compute_table_name
-
else
-
compute_table_name
-
end
-
end
-
-
1
def full_table_name_prefix #:nodoc:
-
(parents.detect{ |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix
-
end
-
-
# Defines the name of the table column which will store the class name on single-table
-
# inheritance situations.
-
#
-
# The default inheritance column name is +type+, which means it's a
-
# reserved word inside Active Record. To be able to use single-table
-
# inheritance with another column name, or to use the column +type+ in
-
# your own model for something else, you can set +inheritance_column+:
-
#
-
# self.inheritance_column = 'zoink'
-
1
def inheritance_column
-
(@inheritance_column ||= nil) || superclass.inheritance_column
-
end
-
-
# Sets the value of inheritance_column
-
1
def inheritance_column=(value)
-
1
@inheritance_column = value.to_s
-
1
@explicit_inheritance_column = true
-
end
-
-
1
def sequence_name
-
if base_class == self
-
@sequence_name ||= reset_sequence_name
-
else
-
(@sequence_name ||= nil) || base_class.sequence_name
-
end
-
end
-
-
1
def reset_sequence_name #:nodoc:
-
@explicit_sequence_name = false
-
@sequence_name = connection.default_sequence_name(table_name, primary_key)
-
end
-
-
# Sets the name of the sequence to use when generating ids to the given
-
# value, or (if the value is nil or false) to the value returned by the
-
# given block. This is required for Oracle and is useful for any
-
# database which relies on sequences for primary key generation.
-
#
-
# If a sequence name is not explicitly set when using Oracle or Firebird,
-
# it will default to the commonly used pattern of: #{table_name}_seq
-
#
-
# If a sequence name is not explicitly set when using PostgreSQL, it
-
# will discover the sequence corresponding to your primary key for you.
-
#
-
# class Project < ActiveRecord::Base
-
# self.sequence_name = "projectseq" # default would have been "project_seq"
-
# end
-
1
def sequence_name=(value)
-
@sequence_name = value.to_s
-
@explicit_sequence_name = true
-
end
-
-
# Indicates whether the table associated with this class exists
-
1
def table_exists?
-
connection.schema_cache.table_exists?(table_name)
-
end
-
-
# Returns an array of column objects for the table associated with this class.
-
1
def columns
-
@columns ||= connection.schema_cache.columns[table_name].map do |col|
-
col = col.dup
-
col.primary = (col.name == primary_key)
-
col
-
end
-
end
-
-
# Returns a hash of column objects for the table associated with this class.
-
1
def columns_hash
-
@columns_hash ||= Hash[columns.map { |c| [c.name, c] }]
-
end
-
-
1
def column_types # :nodoc:
-
@column_types ||= decorate_columns(columns_hash.dup)
-
end
-
-
1
def decorate_columns(columns_hash) # :nodoc:
-
return if columns_hash.empty?
-
-
serialized_attributes.each_key do |key|
-
columns_hash[key] = AttributeMethods::Serialization::Type.new(columns_hash[key])
-
end
-
-
columns_hash.each do |name, col|
-
if create_time_zone_conversion_attribute?(name, col)
-
columns_hash[name] = AttributeMethods::TimeZoneConversion::Type.new(col)
-
end
-
end
-
-
columns_hash
-
end
-
-
# Returns a hash where the keys are column names and the values are
-
# default values when instantiating the AR object for this table.
-
1
def column_defaults
-
@column_defaults ||= Hash[columns.map { |c| [c.name, c.default] }]
-
end
-
-
# Returns an array of column names as strings.
-
1
def column_names
-
@column_names ||= columns.map { |column| column.name }
-
end
-
-
# Returns an array of column objects where the primary id, all columns ending in "_id" or "_count",
-
# and columns used for single table inheritance have been removed.
-
1
def content_columns
-
@content_columns ||= columns.reject { |c| c.primary || c.name =~ /(_id|_count)$/ || c.name == inheritance_column }
-
end
-
-
# Returns a hash of all the methods added to query each of the columns in the table with the name of the method as the key
-
# and true as the value. This makes it possible to do O(1) lookups in respond_to? to check if a given method for attribute
-
# is available.
-
1
def column_methods_hash #:nodoc:
-
@dynamic_methods_hash ||= column_names.each_with_object(Hash.new(false)) do |attr, methods|
-
attr_name = attr.to_s
-
methods[attr.to_sym] = attr_name
-
methods["#{attr}=".to_sym] = attr_name
-
methods["#{attr}?".to_sym] = attr_name
-
methods["#{attr}_before_type_cast".to_sym] = attr_name
-
end
-
end
-
-
# Resets all the cached information about columns, which will cause them
-
# to be reloaded on the next request.
-
#
-
# The most common usage pattern for this method is probably in a migration,
-
# when just after creating a table you want to populate it with some default
-
# values, eg:
-
#
-
# class CreateJobLevels < ActiveRecord::Migration
-
# def up
-
# create_table :job_levels do |t|
-
# t.integer :id
-
# t.string :name
-
#
-
# t.timestamps
-
# end
-
#
-
# JobLevel.reset_column_information
-
# %w{assistant executive manager director}.each do |type|
-
# JobLevel.create(:name => type)
-
# end
-
# end
-
#
-
# def down
-
# drop_table :job_levels
-
# end
-
# end
-
1
def reset_column_information
-
connection.clear_cache!
-
undefine_attribute_methods
-
connection.schema_cache.clear_table_cache!(table_name) if table_exists?
-
-
@arel_engine = nil
-
@column_defaults = nil
-
@column_names = nil
-
@columns = nil
-
@columns_hash = nil
-
@column_types = nil
-
@content_columns = nil
-
@dynamic_methods_hash = nil
-
@inheritance_column = nil unless defined?(@explicit_inheritance_column) && @explicit_inheritance_column
-
@relation = nil
-
end
-
-
# This is a hook for use by modules that need to do extra stuff to
-
# attributes when they are initialized. (e.g. attribute
-
# serialization)
-
1
def initialize_attributes(attributes, options = {}) #:nodoc:
-
attributes
-
end
-
-
1
private
-
-
# Guesses the table name, but does not decorate it with prefix and suffix information.
-
1
def undecorated_table_name(class_name = base_class.name)
-
table_name = class_name.to_s.demodulize.underscore
-
pluralize_table_names ? table_name.pluralize : table_name
-
end
-
-
# Computes and returns a table name according to default conventions.
-
1
def compute_table_name
-
base = base_class
-
if self == base
-
# Nested classes are prefixed with singular parent table name.
-
if parent < Base && !parent.abstract_class?
-
contained = parent.table_name
-
contained = contained.singularize if parent.pluralize_table_names
-
contained += '_'
-
end
-
"#{full_table_name_prefix}#{contained}#{undecorated_table_name(name)}#{table_name_suffix}"
-
else
-
# STI subclasses always use their superclass' table.
-
base.table_name
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/object/try'
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
-
1
module ActiveRecord
-
1
module NestedAttributes #:nodoc:
-
1
class TooManyRecords < ActiveRecordError
-
end
-
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :nested_attributes_options, instance_writer: false
-
1
self.nested_attributes_options = {}
-
end
-
-
# = Active Record Nested Attributes
-
#
-
# Nested attributes allow you to save attributes on associated records
-
# through the parent. By default nested attribute updating is turned off
-
# and you can enable it using the accepts_nested_attributes_for class
-
# method. When you enable nested attributes an attribute writer is
-
# defined on the model.
-
#
-
# The attribute writer is named after the association, which means that
-
# in the following example, two new methods are added to your model:
-
#
-
# <tt>author_attributes=(attributes)</tt> and
-
# <tt>pages_attributes=(attributes)</tt>.
-
#
-
# class Book < ActiveRecord::Base
-
# has_one :author
-
# has_many :pages
-
#
-
# accepts_nested_attributes_for :author, :pages
-
# end
-
#
-
# Note that the <tt>:autosave</tt> option is automatically enabled on every
-
# association that accepts_nested_attributes_for is used for.
-
#
-
# === One-to-one
-
#
-
# Consider a Member model that has one Avatar:
-
#
-
# class Member < ActiveRecord::Base
-
# has_one :avatar
-
# accepts_nested_attributes_for :avatar
-
# end
-
#
-
# Enabling nested attributes on a one-to-one association allows you to
-
# create the member and avatar in one go:
-
#
-
# params = { :member => { :name => 'Jack', :avatar_attributes => { :icon => 'smiling' } } }
-
# member = Member.create(params[:member])
-
# member.avatar.id # => 2
-
# member.avatar.icon # => 'smiling'
-
#
-
# It also allows you to update the avatar through the member:
-
#
-
# params = { :member => { :avatar_attributes => { :id => '2', :icon => 'sad' } } }
-
# member.update_attributes params[:member]
-
# member.avatar.icon # => 'sad'
-
#
-
# By default you will only be able to set and update attributes on the
-
# associated model. If you want to destroy the associated model through the
-
# attributes hash, you have to enable it first using the
-
# <tt>:allow_destroy</tt> option.
-
#
-
# class Member < ActiveRecord::Base
-
# has_one :avatar
-
# accepts_nested_attributes_for :avatar, :allow_destroy => true
-
# end
-
#
-
# Now, when you add the <tt>_destroy</tt> key to the attributes hash, with a
-
# value that evaluates to +true+, you will destroy the associated model:
-
#
-
# member.avatar_attributes = { :id => '2', :_destroy => '1' }
-
# member.avatar.marked_for_destruction? # => true
-
# member.save
-
# member.reload.avatar # => nil
-
#
-
# Note that the model will _not_ be destroyed until the parent is saved.
-
#
-
# === One-to-many
-
#
-
# Consider a member that has a number of posts:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts
-
# end
-
#
-
# You can now set or update attributes on an associated post model through
-
# the attribute hash.
-
#
-
# For each hash that does _not_ have an <tt>id</tt> key a new record will
-
# be instantiated, unless the hash also contains a <tt>_destroy</tt> key
-
# that evaluates to +true+.
-
#
-
# params = { :member => {
-
# :name => 'joe', :posts_attributes => [
-
# { :title => 'Kari, the awesome Ruby documentation browser!' },
-
# { :title => 'The egalitarian assumption of the modern citizen' },
-
# { :title => '', :_destroy => '1' } # this will be ignored
-
# ]
-
# }}
-
#
-
# member = Member.create(params[:member])
-
# member.posts.length # => 2
-
# member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
-
# member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
-
#
-
# You may also set a :reject_if proc to silently ignore any new record
-
# hashes if they fail to pass your criteria. For example, the previous
-
# example could be rewritten as:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, :reject_if => proc { |attributes| attributes['title'].blank? }
-
# end
-
#
-
# params = { :member => {
-
# :name => 'joe', :posts_attributes => [
-
# { :title => 'Kari, the awesome Ruby documentation browser!' },
-
# { :title => 'The egalitarian assumption of the modern citizen' },
-
# { :title => '' } # this will be ignored because of the :reject_if proc
-
# ]
-
# }}
-
#
-
# member = Member.create(params[:member])
-
# member.posts.length # => 2
-
# member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
-
# member.posts.second.title # => 'The egalitarian assumption of the modern citizen'
-
#
-
# Alternatively, :reject_if also accepts a symbol for using methods:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, :reject_if => :new_record?
-
# end
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, :reject_if => :reject_posts
-
#
-
# def reject_posts(attributed)
-
# attributed['title'].blank?
-
# end
-
# end
-
#
-
# If the hash contains an <tt>id</tt> key that matches an already
-
# associated record, the matching record will be modified:
-
#
-
# member.attributes = {
-
# :name => 'Joe',
-
# :posts_attributes => [
-
# { :id => 1, :title => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
-
# { :id => 2, :title => '[UPDATED] other post' }
-
# ]
-
# }
-
#
-
# member.posts.first.title # => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!'
-
# member.posts.second.title # => '[UPDATED] other post'
-
#
-
# By default the associated records are protected from being destroyed. If
-
# you want to destroy any of the associated records through the attributes
-
# hash, you have to enable it first using the <tt>:allow_destroy</tt>
-
# option. This will allow you to also use the <tt>_destroy</tt> key to
-
# destroy existing records:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts
-
# accepts_nested_attributes_for :posts, :allow_destroy => true
-
# end
-
#
-
# params = { :member => {
-
# :posts_attributes => [{ :id => '2', :_destroy => '1' }]
-
# }}
-
#
-
# member.attributes = params[:member]
-
# member.posts.detect { |p| p.id == 2 }.marked_for_destruction? # => true
-
# member.posts.length # => 2
-
# member.save
-
# member.reload.posts.length # => 1
-
#
-
# === Saving
-
#
-
# All changes to models, including the destruction of those marked for
-
# destruction, are saved and destroyed automatically and atomically when
-
# the parent model is saved. This happens inside the transaction initiated
-
# by the parents save method. See ActiveRecord::AutosaveAssociation.
-
#
-
# === Validating the presence of a parent model
-
#
-
# If you want to validate that a child record is associated with a parent
-
# record, you can use <tt>validates_presence_of</tt> and
-
# <tt>inverse_of</tt> as this example illustrates:
-
#
-
# class Member < ActiveRecord::Base
-
# has_many :posts, :inverse_of => :member
-
# accepts_nested_attributes_for :posts
-
# end
-
#
-
# class Post < ActiveRecord::Base
-
# belongs_to :member, :inverse_of => :posts
-
# validates_presence_of :member
-
# end
-
1
module ClassMethods
-
1
REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |key, value| key == '_destroy' || value.blank? } }
-
-
# Defines an attributes writer for the specified association(s).
-
#
-
# Supported options:
-
# [:allow_destroy]
-
# If true, destroys any members from the attributes hash with a
-
# <tt>_destroy</tt> key and a value that evaluates to +true+
-
# (eg. 1, '1', true, or 'true'). This option is off by default.
-
# [:reject_if]
-
# Allows you to specify a Proc or a Symbol pointing to a method
-
# that checks whether a record should be built for a certain attribute
-
# hash. The hash is passed to the supplied Proc or the method
-
# and it should return either +true+ or +false+. When no :reject_if
-
# is specified, a record will be built for all attribute hashes that
-
# do not have a <tt>_destroy</tt> value that evaluates to true.
-
# Passing <tt>:all_blank</tt> instead of a Proc will create a proc
-
# that will reject a record where all the attributes are blank excluding
-
# any value for _destroy.
-
# [:limit]
-
# Allows you to specify the maximum number of the associated records that
-
# can be processed with the nested attributes. Limit also can be specified as a
-
# Proc or a Symbol pointing to a method that should return number. If the size of the
-
# nested attributes array exceeds the specified limit, NestedAttributes::TooManyRecords
-
# exception is raised. If omitted, any number associations can be processed.
-
# Note that the :limit option is only applicable to one-to-many associations.
-
# [:update_only]
-
# For a one-to-one association, this option allows you to specify how
-
# nested attributes are to be used when an associated record already
-
# exists. In general, an existing record may either be updated with the
-
# new set of attribute values or be replaced by a wholly new record
-
# containing those values. By default the :update_only option is +false+
-
# and the nested attributes are used to update the existing record only
-
# if they include the record's <tt>:id</tt> value. Otherwise a new
-
# record will be instantiated and used to replace the existing one.
-
# However if the :update_only option is +true+, the nested attributes
-
# are used to update the record's attributes always, regardless of
-
# whether the <tt>:id</tt> is present. The option is ignored for collection
-
# associations.
-
#
-
# Examples:
-
# # creates avatar_attributes=
-
# accepts_nested_attributes_for :avatar, :reject_if => proc { |attributes| attributes['name'].blank? }
-
# # creates avatar_attributes=
-
# accepts_nested_attributes_for :avatar, :reject_if => :all_blank
-
# # creates avatar_attributes= and posts_attributes=
-
# accepts_nested_attributes_for :avatar, :posts, :allow_destroy => true
-
1
def accepts_nested_attributes_for(*attr_names)
-
options = { :allow_destroy => false, :update_only => false }
-
options.update(attr_names.extract_options!)
-
options.assert_valid_keys(:allow_destroy, :reject_if, :limit, :update_only)
-
options[:reject_if] = REJECT_ALL_BLANK_PROC if options[:reject_if] == :all_blank
-
-
attr_names.each do |association_name|
-
if reflection = reflect_on_association(association_name)
-
reflection.options[:autosave] = true
-
add_autosave_association_callbacks(reflection)
-
-
nested_attributes_options = self.nested_attributes_options.dup
-
nested_attributes_options[association_name.to_sym] = options
-
self.nested_attributes_options = nested_attributes_options
-
-
type = (reflection.collection? ? :collection : :one_to_one)
-
-
# def pirate_attributes=(attributes)
-
# assign_nested_attributes_for_one_to_one_association(:pirate, attributes, mass_assignment_options)
-
# end
-
generated_feature_methods.module_eval <<-eoruby, __FILE__, __LINE__ + 1
-
if method_defined?(:#{association_name}_attributes=)
-
remove_method(:#{association_name}_attributes=)
-
end
-
def #{association_name}_attributes=(attributes)
-
assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes)
-
end
-
eoruby
-
else
-
raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?"
-
end
-
end
-
end
-
end
-
-
# Returns ActiveRecord::AutosaveAssociation::marked_for_destruction? It's
-
# used in conjunction with fields_for to build a form element for the
-
# destruction of this association.
-
#
-
# See ActionView::Helpers::FormHelper::fields_for for more info.
-
1
def _destroy
-
marked_for_destruction?
-
end
-
-
1
private
-
-
# Attribute hash keys that should not be assigned as normal attributes.
-
# These hash keys are nested attributes implementation details.
-
1
UNASSIGNABLE_KEYS = %w( id _destroy )
-
-
# Assigns the given attributes to the association.
-
#
-
# If an associated record does not yet exist, one will be instantiated. If
-
# an associated record already exists, the method's behavior depends on
-
# the value of the update_only option. If update_only is +false+ and the
-
# given attributes include an <tt>:id</tt> that matches the existing record's
-
# id, then the existing record will be modified. If no <tt>:id</tt> is provided
-
# it will be replaced with a new record. If update_only is +true+ the existing
-
# record will be modified regardless of whether an <tt>:id</tt> is provided.
-
#
-
# If the given attributes include a matching <tt>:id</tt> attribute, or
-
# update_only is true, and a <tt>:_destroy</tt> key set to a truthy value,
-
# then the existing record will be marked for destruction.
-
1
def assign_nested_attributes_for_one_to_one_association(association_name, attributes)
-
options = self.nested_attributes_options[association_name]
-
attributes = attributes.with_indifferent_access
-
-
if (options[:update_only] || !attributes['id'].blank?) && (record = send(association_name)) &&
-
(options[:update_only] || record.id.to_s == attributes['id'].to_s)
-
assign_to_or_mark_for_destruction(record, attributes, options[:allow_destroy]) unless call_reject_if(association_name, attributes)
-
-
elsif attributes['id'].present?
-
raise_nested_attributes_record_not_found(association_name, attributes['id'])
-
-
elsif !reject_new_record?(association_name, attributes)
-
method = "build_#{association_name}"
-
if respond_to?(method)
-
send(method, attributes.except(*UNASSIGNABLE_KEYS))
-
else
-
raise ArgumentError, "Cannot build association `#{association_name}'. Are you trying to build a polymorphic one-to-one association?"
-
end
-
end
-
end
-
-
# Assigns the given attributes to the collection association.
-
#
-
# Hashes with an <tt>:id</tt> value matching an existing associated record
-
# will update that record. Hashes without an <tt>:id</tt> value will build
-
# a new record for the association. Hashes with a matching <tt>:id</tt>
-
# value and a <tt>:_destroy</tt> key set to a truthy value will mark the
-
# matched record for destruction.
-
#
-
# For example:
-
#
-
# assign_nested_attributes_for_collection_association(:people, {
-
# '1' => { :id => '1', :name => 'Peter' },
-
# '2' => { :name => 'John' },
-
# '3' => { :id => '2', :_destroy => true }
-
# })
-
#
-
# Will update the name of the Person with ID 1, build a new associated
-
# person with the name 'John', and mark the associated Person with ID 2
-
# for destruction.
-
#
-
# Also accepts an Array of attribute hashes:
-
#
-
# assign_nested_attributes_for_collection_association(:people, [
-
# { :id => '1', :name => 'Peter' },
-
# { :name => 'John' },
-
# { :id => '2', :_destroy => true }
-
# ])
-
1
def assign_nested_attributes_for_collection_association(association_name, attributes_collection)
-
options = self.nested_attributes_options[association_name]
-
-
unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array)
-
raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})"
-
end
-
-
if limit = options[:limit]
-
limit = case limit
-
when Symbol
-
send(limit)
-
when Proc
-
limit.call
-
else
-
limit
-
end
-
-
if limit && attributes_collection.size > limit
-
raise TooManyRecords, "Maximum #{limit} records are allowed. Got #{attributes_collection.size} records instead."
-
end
-
end
-
-
if attributes_collection.is_a? Hash
-
keys = attributes_collection.keys
-
attributes_collection = if keys.include?('id') || keys.include?(:id)
-
[attributes_collection]
-
else
-
attributes_collection.values
-
end
-
end
-
-
association = association(association_name)
-
-
existing_records = if association.loaded?
-
association.target
-
else
-
attribute_ids = attributes_collection.map {|a| a['id'] || a[:id] }.compact
-
attribute_ids.empty? ? [] : association.scope.where(association.klass.primary_key => attribute_ids)
-
end
-
-
attributes_collection.each do |attributes|
-
attributes = attributes.with_indifferent_access
-
-
if attributes['id'].blank?
-
unless reject_new_record?(association_name, attributes)
-
association.build(attributes.except(*UNASSIGNABLE_KEYS))
-
end
-
elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes['id'].to_s }
-
unless association.loaded? || call_reject_if(association_name, attributes)
-
# Make sure we are operating on the actual object which is in the association's
-
# proxy_target array (either by finding it, or adding it if not found)
-
target_record = association.target.detect { |record| record == existing_record }
-
-
if target_record
-
existing_record = target_record
-
else
-
association.add_to_target(existing_record)
-
end
-
end
-
-
if !call_reject_if(association_name, attributes)
-
assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy])
-
end
-
else
-
raise_nested_attributes_record_not_found(association_name, attributes['id'])
-
end
-
end
-
end
-
-
# Updates a record with the +attributes+ or marks it for destruction if
-
# +allow_destroy+ is +true+ and has_destroy_flag? returns +true+.
-
1
def assign_to_or_mark_for_destruction(record, attributes, allow_destroy)
-
record.assign_attributes(attributes.except(*UNASSIGNABLE_KEYS))
-
record.mark_for_destruction if has_destroy_flag?(attributes) && allow_destroy
-
end
-
-
# Determines if a hash contains a truthy _destroy key.
-
1
def has_destroy_flag?(hash)
-
ConnectionAdapters::Column.value_to_boolean(hash['_destroy'])
-
end
-
-
# Determines if a new record should be build by checking for
-
# has_destroy_flag? or if a <tt>:reject_if</tt> proc exists for this
-
# association and evaluates to +true+.
-
1
def reject_new_record?(association_name, attributes)
-
has_destroy_flag?(attributes) || call_reject_if(association_name, attributes)
-
end
-
-
1
def call_reject_if(association_name, attributes)
-
return false if has_destroy_flag?(attributes)
-
case callback = self.nested_attributes_options[association_name][:reject_if]
-
when Symbol
-
method(callback).arity == 0 ? send(callback) : send(callback, attributes)
-
when Proc
-
callback.call(attributes)
-
end
-
end
-
-
1
def raise_nested_attributes_record_not_found(association_name, record_id)
-
raise RecordNotFound, "Couldn't find #{self.class.reflect_on_association(association_name).klass.name} with ID=#{record_id} for #{self.class.name} with ID=#{id}"
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record Persistence
-
1
module Persistence
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
# Creates an object (or multiple objects) and saves it to the database, if validations pass.
-
# The resulting object is returned whether the object was saved successfully to the database or not.
-
#
-
# The +attributes+ parameter can be either a Hash or an Array of Hashes. These Hashes describe the
-
# attributes on the objects that are to be created.
-
#
-
# +create+ respects mass-assignment security and accepts either +:as+ or +:without_protection+ options
-
# in the +options+ parameter.
-
#
-
# ==== Examples
-
# # Create a single new object
-
# User.create(first_name: 'Jamie')
-
#
-
# # Create an Array of new objects
-
# User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }])
-
#
-
# # Create a single object and pass it into a block to set other attributes.
-
# User.create(first_name: 'Jamie') do |u|
-
# u.is_admin = false
-
# end
-
#
-
# # Creating an Array of new objects using a block, where the block is executed for each object:
-
# User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }]) do |u|
-
# u.is_admin = false
-
# end
-
1
def create(attributes = nil, &block)
-
if attributes.is_a?(Array)
-
attributes.collect { |attr| create(attr, &block) }
-
else
-
object = new(attributes, &block)
-
object.save
-
object
-
end
-
end
-
end
-
-
# Returns true if this object hasn't been saved yet -- that is, a record
-
# for the object doesn't exist in the data store yet; otherwise, returns false.
-
1
def new_record?
-
@new_record
-
end
-
-
# Returns true if this object has been destroyed, otherwise returns false.
-
1
def destroyed?
-
@destroyed
-
end
-
-
# Returns true if the record is persisted, i.e. it's not a new record and it was
-
# not destroyed, otherwise returns false.
-
1
def persisted?
-
!(new_record? || destroyed?)
-
end
-
-
# Saves the model.
-
#
-
# If the model is new a record gets created in the database, otherwise
-
# the existing record gets updated.
-
#
-
# By default, save always run validations. If any of them fail the action
-
# is cancelled and +save+ returns +false+. However, if you supply
-
# validate: false, validations are bypassed altogether. See
-
# ActiveRecord::Validations for more information.
-
#
-
# There's a series of callbacks associated with +save+. If any of the
-
# <tt>before_*</tt> callbacks return +false+ the action is cancelled and
-
# +save+ returns +false+. See ActiveRecord::Callbacks for further
-
# details.
-
1
def save(*)
-
begin
-
create_or_update
-
rescue ActiveRecord::RecordInvalid
-
false
-
end
-
end
-
-
# Saves the model.
-
#
-
# If the model is new a record gets created in the database, otherwise
-
# the existing record gets updated.
-
#
-
# With <tt>save!</tt> validations always run. If any of them fail
-
# ActiveRecord::RecordInvalid gets raised. See ActiveRecord::Validations
-
# for more information.
-
#
-
# There's a series of callbacks associated with <tt>save!</tt>. If any of
-
# the <tt>before_*</tt> callbacks return +false+ the action is cancelled
-
# and <tt>save!</tt> raises ActiveRecord::RecordNotSaved. See
-
# ActiveRecord::Callbacks for further details.
-
1
def save!(*)
-
create_or_update || raise(RecordNotSaved)
-
end
-
-
# Deletes the record in the database and freezes this instance to
-
# reflect that no changes should be made (since they can't be
-
# persisted). Returns the frozen instance.
-
#
-
# The row is simply removed with an SQL +DELETE+ statement on the
-
# record's primary key, and no callbacks are executed.
-
#
-
# To enforce the object's +before_destroy+ and +after_destroy+
-
# callbacks, Observer methods, or any <tt>:dependent</tt> association
-
# options, use <tt>#destroy</tt>.
-
1
def delete
-
self.class.delete(id) if persisted?
-
@destroyed = true
-
freeze
-
end
-
-
# Deletes the record in the database and freezes this instance to reflect
-
# that no changes should be made (since they can't be persisted).
-
#
-
# There's a series of callbacks associated with <tt>destroy</tt>. If
-
# the <tt>before_destroy</tt> callback return +false+ the action is cancelled
-
# and <tt>destroy</tt> returns +false+. See
-
# ActiveRecord::Callbacks for further details.
-
1
def destroy
-
raise ReadOnlyRecord if readonly?
-
destroy_associations
-
destroy_row if persisted?
-
@destroyed = true
-
freeze
-
end
-
-
# Deletes the record in the database and freezes this instance to reflect
-
# that no changes should be made (since they can't be persisted).
-
#
-
# There's a series of callbacks associated with <tt>destroy!</tt>. If
-
# the <tt>before_destroy</tt> callback return +false+ the action is cancelled
-
# and <tt>destroy!</tt> raises ActiveRecord::RecordNotDestroyed. See
-
# ActiveRecord::Callbacks for further details.
-
1
def destroy!
-
destroy || raise(ActiveRecord::RecordNotDestroyed)
-
end
-
-
# Returns an instance of the specified +klass+ with the attributes of the
-
# current record. This is mostly useful in relation to single-table
-
# inheritance structures where you want a subclass to appear as the
-
# superclass. This can be used along with record identification in
-
# Action Pack to allow, say, <tt>Client < Company</tt> to do something
-
# like render <tt>partial: @client.becomes(Company)</tt> to render that
-
# instance using the companies/company partial instead of clients/client.
-
#
-
# Note: The new instance will share a link to the same attributes as the original class.
-
# So any change to the attributes in either instance will affect the other.
-
1
def becomes(klass)
-
became = klass.new
-
became.instance_variable_set("@attributes", @attributes)
-
became.instance_variable_set("@attributes_cache", @attributes_cache)
-
became.instance_variable_set("@new_record", new_record?)
-
became.instance_variable_set("@destroyed", destroyed?)
-
became.instance_variable_set("@errors", errors)
-
became.public_send("#{klass.inheritance_column}=", klass.name) unless self.class.descends_from_active_record?
-
became
-
end
-
-
# Updates a single attribute and saves the record.
-
# This is especially useful for boolean flags on existing records. Also note that
-
#
-
# * Validation is skipped.
-
# * Callbacks are invoked.
-
# * updated_at/updated_on column is updated if that column is available.
-
# * Updates all the attributes that are dirty in this object.
-
#
-
1
def update_attribute(name, value)
-
name = name.to_s
-
verify_readonly_attribute(name)
-
send("#{name}=", value)
-
save(:validate => false)
-
end
-
-
# Updates the attributes of the model from the passed-in hash and saves the
-
# record, all wrapped in a transaction. If the object is invalid, the saving
-
# will fail and false will be returned.
-
1
def update_attributes(attributes)
-
# The following transaction covers any possible database side-effects of the
-
# attributes assignment. For example, setting the IDs of a child collection.
-
with_transaction_returning_status do
-
assign_attributes(attributes)
-
save
-
end
-
end
-
-
# Updates its receiver just like +update_attributes+ but calls <tt>save!</tt> instead
-
# of +save+, so an exception is raised if the record is invalid.
-
1
def update_attributes!(attributes)
-
# The following transaction covers any possible database side-effects of the
-
# attributes assignment. For example, setting the IDs of a child collection.
-
with_transaction_returning_status do
-
assign_attributes(attributes)
-
save!
-
end
-
end
-
-
# Updates a single attribute of an object, without having to explicitly call save on that object.
-
#
-
# * Validation is skipped.
-
# * Callbacks are skipped.
-
# * updated_at/updated_on column is not updated if that column is available.
-
#
-
# Raises an +ActiveRecordError+ when called on new objects, or when the +name+
-
# attribute is marked as readonly.
-
1
def update_column(name, value)
-
update_columns(name => value)
-
end
-
-
# Updates the attributes from the passed-in hash, without having to explicitly call save on that object.
-
#
-
# * Validation is skipped.
-
# * Callbacks are skipped.
-
# * updated_at/updated_on column is not updated if that column is available.
-
#
-
# Raises an +ActiveRecordError+ when called on new objects, or when at least
-
# one of the attributes is marked as readonly.
-
1
def update_columns(attributes)
-
raise ActiveRecordError, "can not update on a new record object" unless persisted?
-
-
attributes.each_key do |key|
-
verify_readonly_attribute(key.to_s)
-
end
-
-
updated_count = self.class.where(self.class.primary_key => id).update_all(attributes)
-
-
attributes.each do |k,v|
-
raw_write_attribute(k,v)
-
end
-
-
updated_count == 1
-
end
-
-
# Initializes +attribute+ to zero if +nil+ and adds the value passed as +by+ (default is 1).
-
# The increment is performed directly on the underlying attribute, no setter is invoked.
-
# Only makes sense for number-based attributes. Returns +self+.
-
1
def increment(attribute, by = 1)
-
self[attribute] ||= 0
-
self[attribute] += by
-
self
-
end
-
-
# Wrapper around +increment+ that saves the record. This method differs from
-
# its non-bang version in that it passes through the attribute setter.
-
# Saving is not subjected to validation checks. Returns +true+ if the
-
# record could be saved.
-
1
def increment!(attribute, by = 1)
-
increment(attribute, by).update_attribute(attribute, self[attribute])
-
end
-
-
# Initializes +attribute+ to zero if +nil+ and subtracts the value passed as +by+ (default is 1).
-
# The decrement is performed directly on the underlying attribute, no setter is invoked.
-
# Only makes sense for number-based attributes. Returns +self+.
-
1
def decrement(attribute, by = 1)
-
self[attribute] ||= 0
-
self[attribute] -= by
-
self
-
end
-
-
# Wrapper around +decrement+ that saves the record. This method differs from
-
# its non-bang version in that it passes through the attribute setter.
-
# Saving is not subjected to validation checks. Returns +true+ if the
-
# record could be saved.
-
1
def decrement!(attribute, by = 1)
-
decrement(attribute, by).update_attribute(attribute, self[attribute])
-
end
-
-
# Assigns to +attribute+ the boolean opposite of <tt>attribute?</tt>. So
-
# if the predicate returns +true+ the attribute will become +false+. This
-
# method toggles directly the underlying value without calling any setter.
-
# Returns +self+.
-
1
def toggle(attribute)
-
self[attribute] = !send("#{attribute}?")
-
self
-
end
-
-
# Wrapper around +toggle+ that saves the record. This method differs from
-
# its non-bang version in that it passes through the attribute setter.
-
# Saving is not subjected to validation checks. Returns +true+ if the
-
# record could be saved.
-
1
def toggle!(attribute)
-
toggle(attribute).update_attribute(attribute, self[attribute])
-
end
-
-
# Reloads the attributes of this object from the database.
-
# The optional options argument is passed to find when reloading so you
-
# may do e.g. record.reload(lock: true) to reload the same record with
-
# an exclusive row lock.
-
1
def reload(options = nil)
-
clear_aggregation_cache
-
clear_association_cache
-
-
fresh_object =
-
if options && options[:lock]
-
self.class.unscoped { self.class.lock.find(id) }
-
else
-
self.class.unscoped { self.class.find(id) }
-
end
-
-
@attributes.update(fresh_object.instance_variable_get('@attributes'))
-
@columns_hash = fresh_object.instance_variable_get('@columns_hash')
-
-
@attributes_cache = {}
-
self
-
end
-
-
# Saves the record with the updated_at/on attributes set to the current time.
-
# Please note that no validation is performed and no callbacks are executed.
-
# If an attribute name is passed, that attribute is updated along with
-
# updated_at/on attributes.
-
#
-
# product.touch # updates updated_at/on
-
# product.touch(:designed_at) # updates the designed_at attribute and updated_at/on
-
#
-
# If used along with +belongs_to+ then +touch+ will invoke +touch+ method on associated object.
-
#
-
# class Brake < ActiveRecord::Base
-
# belongs_to :car, touch: true
-
# end
-
#
-
# class Car < ActiveRecord::Base
-
# belongs_to :corporation, touch: true
-
# end
-
#
-
# # triggers @brake.car.touch and @brake.car.corporation.touch
-
# @brake.touch
-
1
def touch(name = nil)
-
attributes = timestamp_attributes_for_update_in_model
-
attributes << name if name
-
-
unless attributes.empty?
-
current_time = current_time_from_proper_timezone
-
changes = {}
-
-
attributes.each do |column|
-
column = column.to_s
-
changes[column] = write_attribute(column, current_time)
-
end
-
-
changes[self.class.locking_column] = increment_lock if locking_enabled?
-
-
@changed_attributes.except!(*changes.keys)
-
primary_key = self.class.primary_key
-
self.class.unscoped.where(primary_key => self[primary_key]).update_all(changes) == 1
-
end
-
end
-
-
1
private
-
-
# A hook to be overridden by association modules.
-
1
def destroy_associations
-
end
-
-
1
def destroy_row
-
relation_for_destroy.delete_all
-
end
-
-
1
def relation_for_destroy
-
pk = self.class.primary_key
-
column = self.class.columns_hash[pk]
-
substitute = connection.substitute_at(column, 0)
-
-
relation = self.class.unscoped.where(
-
self.class.arel_table[pk].eq(substitute))
-
-
relation.bind_values = [[column, id]]
-
relation
-
end
-
-
1
def create_or_update
-
raise ReadOnlyRecord if readonly?
-
result = new_record? ? create : update
-
result != false
-
end
-
-
# Updates the associated record with values matching those of the instance attributes.
-
# Returns the number of affected rows.
-
1
def update(attribute_names = @attributes.keys)
-
attributes_with_values = arel_attributes_with_values_for_update(attribute_names)
-
return 0 if attributes_with_values.empty?
-
klass = self.class
-
stmt = klass.unscoped.where(klass.arel_table[klass.primary_key].eq(id)).arel.compile_update(attributes_with_values)
-
klass.connection.update stmt
-
end
-
-
# Creates a record with values matching those of the instance attributes
-
# and returns its id.
-
1
def create(attribute_names = @attributes.keys)
-
attributes_values = arel_attributes_with_values_for_create(attribute_names)
-
-
new_id = self.class.unscoped.insert attributes_values
-
self.id ||= new_id if self.class.primary_key
-
-
@new_record = false
-
id
-
end
-
-
1
def verify_readonly_attribute(name)
-
raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
-
end
-
end
-
end
-
-
1
module ActiveRecord
-
# = Active Record Query Cache
-
1
class QueryCache
-
1
module ClassMethods
-
# Enable the query cache within the block if Active Record is configured.
-
1
def cache(&block)
-
if ActiveRecord::Base.connected?
-
connection.cache(&block)
-
else
-
yield
-
end
-
end
-
-
# Disable the query cache within the block if Active Record is configured.
-
1
def uncached(&block)
-
if ActiveRecord::Base.connected?
-
connection.uncached(&block)
-
else
-
yield
-
end
-
end
-
end
-
-
1
def initialize(app)
-
@app = app
-
end
-
-
1
def call(env)
-
enabled = ActiveRecord::Base.connection.query_cache_enabled
-
connection_id = ActiveRecord::Base.connection_id
-
ActiveRecord::Base.connection.enable_query_cache!
-
-
response = @app.call(env)
-
response[2] = Rack::BodyProxy.new(response[2]) do
-
restore_query_cache_settings(connection_id, enabled)
-
end
-
-
response
-
rescue Exception => e
-
restore_query_cache_settings(connection_id, enabled)
-
raise e
-
end
-
-
1
private
-
-
1
def restore_query_cache_settings(connection_id, enabled)
-
ActiveRecord::Base.connection_id = connection_id
-
ActiveRecord::Base.connection.clear_query_cache
-
ActiveRecord::Base.connection.disable_query_cache! unless enabled
-
end
-
-
end
-
end
-
-
1
module ActiveRecord
-
1
module Querying
-
1
delegate :find, :take, :take!, :first, :first!, :last, :last!, :exists?, :any?, :many?, :to => :all
-
1
delegate :first_or_create, :first_or_create!, :first_or_initialize, :to => :all
-
1
delegate :find_or_create_by, :find_or_create_by!, :find_or_initialize_by, :to => :all
-
1
delegate :find_by, :find_by!, :to => :all
-
1
delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to => :all
-
1
delegate :find_each, :find_in_batches, :to => :all
-
1
delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins,
-
:where, :preload, :eager_load, :includes, :from, :lock, :readonly,
-
:having, :create_with, :uniq, :references, :none, :to => :all
-
1
delegate :count, :average, :minimum, :maximum, :sum, :calculate, :pluck, :ids, :to => :all
-
-
# Executes a custom SQL query against your database and returns all the results. The results will
-
# be returned as an array with columns requested encapsulated as attributes of the model you call
-
# this method from. If you call <tt>Product.find_by_sql</tt> then the results will be returned in
-
# a Product object with the attributes you specified in the SQL query.
-
#
-
# If you call a complicated SQL query which spans multiple tables the columns specified by the
-
# SELECT will be attributes of the model, whether or not they are columns of the corresponding
-
# table.
-
#
-
# The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be
-
# no database agnostic conversions performed. This should be a last resort because using, for example,
-
# MySQL specific terms will lock you to using that particular database engine or require you to
-
# change your call if you switch engines.
-
#
-
# ==== Examples
-
# # A simple SQL query spanning multiple tables
-
# Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
-
# > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
-
#
-
# # You can use the same string replacement techniques as you can with ActiveRecord#find
-
# Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]
-
# > [#<Post:0x36bff9c @attributes={"title"=>"The Cheap Man Buys Twice"}>, ...]
-
1
def find_by_sql(sql, binds = [])
-
logging_query_plan do
-
result_set = connection.select_all(sanitize_sql(sql), "#{name} Load", binds)
-
column_types = {}
-
-
if result_set.respond_to? :column_types
-
column_types = result_set.column_types
-
else
-
ActiveSupport::Deprecation.warn "the object returned from `select_all` must respond to `column_types`"
-
end
-
-
result_set.map { |record| instantiate(record, column_types) }
-
end
-
end
-
-
# Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
-
# The use of this method should be restricted to complicated SQL queries that can't be executed
-
# using the ActiveRecord::Calculations class methods. Look into those before using this.
-
#
-
# ==== Parameters
-
#
-
# * +sql+ - An SQL statement which should return a count query from the database, see the example below.
-
#
-
# ==== Examples
-
#
-
# Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
-
1
def count_by_sql(sql)
-
logging_query_plan do
-
sql = sanitize_conditions(sql)
-
connection.select_value(sql, "#{name} Count").to_i
-
end
-
end
-
end
-
end
-
-
1
module ActiveRecord
-
1
module ReadonlyAttributes
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :_attr_readonly, instance_accessor: false
-
1
self._attr_readonly = []
-
end
-
-
1
module ClassMethods
-
# Attributes listed as readonly will be used to create a new record but update operations will
-
# ignore these fields.
-
1
def attr_readonly(*attributes)
-
self._attr_readonly = Set.new(attributes.map { |a| a.to_s }) + (self._attr_readonly || [])
-
end
-
-
# Returns an array of all the attributes that have been specified as readonly.
-
1
def readonly_attributes
-
self._attr_readonly
-
end
-
end
-
-
1
def _attr_readonly
-
message = "Instance level _attr_readonly method is deprecated, please use class level method."
-
ActiveSupport::Deprecation.warn message
-
defined?(@_attr_readonly) ? @_attr_readonly : self.class._attr_readonly
-
end
-
end
-
end
-
-
1
module ActiveRecord
-
# = Active Record Reflection
-
1
module Reflection # :nodoc:
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :reflections
-
1
self.reflections = {}
-
end
-
-
# Reflection enables to interrogate Active Record classes and objects
-
# about their associations and aggregations. This information can,
-
# for example, be used in a form builder that takes an Active Record object
-
# and creates input fields for all of the attributes depending on their type
-
# and displays the associations to other objects.
-
#
-
# MacroReflection class has info for AggregateReflection and AssociationReflection
-
# classes.
-
1
module ClassMethods
-
1
def create_reflection(macro, name, scope, options, active_record)
-
case macro
-
when :has_many, :belongs_to, :has_one, :has_and_belongs_to_many
-
klass = options[:through] ? ThroughReflection : AssociationReflection
-
reflection = klass.new(macro, name, scope, options, active_record)
-
when :composed_of
-
reflection = AggregateReflection.new(macro, name, scope, options, active_record)
-
end
-
-
self.reflections = self.reflections.merge(name => reflection)
-
reflection
-
end
-
-
# Returns an array of AggregateReflection objects for all the aggregations in the class.
-
1
def reflect_on_all_aggregations
-
reflections.values.grep(AggregateReflection)
-
end
-
-
# Returns the AggregateReflection object for the named +aggregation+ (use the symbol).
-
#
-
# Account.reflect_on_aggregation(:balance) # => the balance AggregateReflection
-
#
-
1
def reflect_on_aggregation(aggregation)
-
reflection = reflections[aggregation]
-
reflection if reflection.is_a?(AggregateReflection)
-
end
-
-
# Returns an array of AssociationReflection objects for all the
-
# associations in the class. If you only want to reflect on a certain
-
# association type, pass in the symbol (<tt>:has_many</tt>, <tt>:has_one</tt>,
-
# <tt>:belongs_to</tt>) as the first parameter.
-
#
-
# Example:
-
#
-
# Account.reflect_on_all_associations # returns an array of all associations
-
# Account.reflect_on_all_associations(:has_many) # returns an array of all has_many associations
-
#
-
1
def reflect_on_all_associations(macro = nil)
-
association_reflections = reflections.values.grep(AssociationReflection)
-
macro ? association_reflections.select { |reflection| reflection.macro == macro } : association_reflections
-
end
-
-
# Returns the AssociationReflection object for the +association+ (use the symbol).
-
#
-
# Account.reflect_on_association(:owner) # returns the owner AssociationReflection
-
# Invoice.reflect_on_association(:line_items).macro # returns :has_many
-
#
-
1
def reflect_on_association(association)
-
reflection = reflections[association]
-
reflection if reflection.is_a?(AssociationReflection)
-
end
-
-
# Returns an array of AssociationReflection objects for all associations which have <tt>:autosave</tt> enabled.
-
1
def reflect_on_all_autosave_associations
-
reflections.values.select { |reflection| reflection.options[:autosave] }
-
end
-
end
-
-
# Abstract base class for AggregateReflection and AssociationReflection. Objects of
-
# AggregateReflection and AssociationReflection are returned by the Reflection::ClassMethods.
-
1
class MacroReflection
-
# Returns the name of the macro.
-
#
-
# <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>:balance</tt>
-
# <tt>has_many :clients</tt> returns <tt>:clients</tt>
-
1
attr_reader :name
-
-
# Returns the macro type.
-
#
-
# <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>:composed_of</tt>
-
# <tt>has_many :clients</tt> returns <tt>:has_many</tt>
-
1
attr_reader :macro
-
-
1
attr_reader :scope
-
-
# Returns the hash of options used for the macro.
-
#
-
# <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>{ class_name: "Money" }</tt>
-
# <tt>has_many :clients</tt> returns +{}+
-
1
attr_reader :options
-
-
1
attr_reader :active_record
-
-
1
attr_reader :plural_name # :nodoc:
-
-
1
def initialize(macro, name, scope, options, active_record)
-
@macro = macro
-
@name = name
-
@scope = scope
-
@options = options
-
@active_record = active_record
-
@plural_name = active_record.pluralize_table_names ?
-
name.to_s.pluralize : name.to_s
-
end
-
-
# Returns the class for the macro.
-
#
-
# <tt>composed_of :balance, class_name: 'Money'</tt> returns the Money class
-
# <tt>has_many :clients</tt> returns the Client class
-
1
def klass
-
@klass ||= class_name.constantize
-
end
-
-
# Returns the class name for the macro.
-
#
-
# <tt>composed_of :balance, class_name: 'Money'</tt> returns <tt>'Money'</tt>
-
# <tt>has_many :clients</tt> returns <tt>'Client'</tt>
-
1
def class_name
-
@class_name ||= (options[:class_name] || derive_class_name).to_s
-
end
-
-
# Returns +true+ if +self+ and +other_aggregation+ have the same +name+ attribute, +active_record+ attribute,
-
# and +other_aggregation+ has an options hash assigned to it.
-
1
def ==(other_aggregation)
-
super ||
-
other_aggregation.kind_of?(self.class) &&
-
name == other_aggregation.name &&
-
other_aggregation.options &&
-
active_record == other_aggregation.active_record
-
end
-
-
1
private
-
1
def derive_class_name
-
name.to_s.camelize
-
end
-
end
-
-
-
# Holds all the meta-data about an aggregation as it was specified in the
-
# Active Record class.
-
1
class AggregateReflection < MacroReflection #:nodoc:
-
1
def mapping
-
mapping = options[:mapping] || [name, name]
-
mapping.first.is_a?(Array) ? mapping : [mapping]
-
end
-
end
-
-
# Holds all the meta-data about an association as it was specified in the
-
# Active Record class.
-
1
class AssociationReflection < MacroReflection #:nodoc:
-
# Returns the target association's class.
-
#
-
# class Author < ActiveRecord::Base
-
# has_many :books
-
# end
-
#
-
# Author.reflect_on_association(:books).klass
-
# # => Book
-
#
-
# <b>Note:</b> Do not call +klass.new+ or +klass.create+ to instantiate
-
# a new association object. Use +build_association+ or +create_association+
-
# instead. This allows plugins to hook into association object creation.
-
1
def klass
-
@klass ||= active_record.send(:compute_type, class_name)
-
end
-
-
1
def initialize(*args)
-
super
-
@collection = [:has_many, :has_and_belongs_to_many].include?(macro)
-
end
-
-
# Returns a new, unsaved instance of the associated class. +options+ will
-
# be passed to the class's constructor.
-
1
def build_association(attributes, &block)
-
klass.new(attributes, &block)
-
end
-
-
1
def table_name
-
@table_name ||= klass.table_name
-
end
-
-
1
def quoted_table_name
-
@quoted_table_name ||= klass.quoted_table_name
-
end
-
-
1
def join_table
-
@join_table ||= options[:join_table] || derive_join_table
-
end
-
-
1
def foreign_key
-
@foreign_key ||= options[:foreign_key] || derive_foreign_key
-
end
-
-
1
def foreign_type
-
@foreign_type ||= options[:foreign_type] || "#{name}_type"
-
end
-
-
1
def type
-
@type ||= options[:as] && "#{options[:as]}_type"
-
end
-
-
1
def primary_key_column
-
@primary_key_column ||= klass.columns.find { |c| c.name == klass.primary_key }
-
end
-
-
1
def association_foreign_key
-
@association_foreign_key ||= options[:association_foreign_key] || class_name.foreign_key
-
end
-
-
# klass option is necessary to support loading polymorphic associations
-
1
def association_primary_key(klass = nil)
-
options[:primary_key] || primary_key(klass || self.klass)
-
end
-
-
1
def active_record_primary_key
-
@active_record_primary_key ||= options[:primary_key] || primary_key(active_record)
-
end
-
-
1
def counter_cache_column
-
if options[:counter_cache] == true
-
"#{active_record.name.demodulize.underscore.pluralize}_count"
-
elsif options[:counter_cache]
-
options[:counter_cache].to_s
-
end
-
end
-
-
1
def columns(tbl_name)
-
@columns ||= klass.connection.columns(tbl_name)
-
end
-
-
1
def reset_column_information
-
@columns = nil
-
end
-
-
1
def check_validity!
-
check_validity_of_inverse!
-
-
if has_and_belongs_to_many? && association_foreign_key == foreign_key
-
raise HasAndBelongsToManyAssociationForeignKeyNeeded.new(self)
-
end
-
end
-
-
1
def check_validity_of_inverse!
-
unless options[:polymorphic]
-
if has_inverse? && inverse_of.nil?
-
raise InverseOfAssociationNotFoundError.new(self)
-
end
-
end
-
end
-
-
1
def through_reflection
-
nil
-
end
-
-
1
def source_reflection
-
nil
-
end
-
-
# A chain of reflections from this one back to the owner. For more see the explanation in
-
# ThroughReflection.
-
1
def chain
-
[self]
-
end
-
-
1
def nested?
-
false
-
end
-
-
# An array of arrays of scopes. Each item in the outside array corresponds to a reflection
-
# in the #chain.
-
1
def scope_chain
-
scope ? [[scope]] : [[]]
-
end
-
-
1
alias :source_macro :macro
-
-
1
def has_inverse?
-
@options[:inverse_of]
-
end
-
-
1
def inverse_of
-
if has_inverse?
-
@inverse_of ||= klass.reflect_on_association(options[:inverse_of])
-
end
-
end
-
-
1
def polymorphic_inverse_of(associated_class)
-
if has_inverse?
-
if inverse_relationship = associated_class.reflect_on_association(options[:inverse_of])
-
inverse_relationship
-
else
-
raise InverseOfAssociationNotFoundError.new(self, associated_class)
-
end
-
end
-
end
-
-
# Returns whether or not this association reflection is for a collection
-
# association. Returns +true+ if the +macro+ is either +has_many+ or
-
# +has_and_belongs_to_many+, +false+ otherwise.
-
1
def collection?
-
@collection
-
end
-
-
# Returns whether or not the association should be validated as part of
-
# the parent's validation.
-
#
-
# Unless you explicitly disable validation with
-
# <tt>validate: false</tt>, validation will take place when:
-
#
-
# * you explicitly enable validation; <tt>validate: true</tt>
-
# * you use autosave; <tt>autosave: true</tt>
-
# * the association is a +has_many+ association
-
1
def validate?
-
!options[:validate].nil? ? options[:validate] : (options[:autosave] == true || macro == :has_many)
-
end
-
-
# Returns +true+ if +self+ is a +belongs_to+ reflection.
-
1
def belongs_to?
-
macro == :belongs_to
-
end
-
-
1
def has_and_belongs_to_many?
-
macro == :has_and_belongs_to_many
-
end
-
-
1
def association_class
-
case macro
-
when :belongs_to
-
if options[:polymorphic]
-
Associations::BelongsToPolymorphicAssociation
-
else
-
Associations::BelongsToAssociation
-
end
-
when :has_and_belongs_to_many
-
Associations::HasAndBelongsToManyAssociation
-
when :has_many
-
if options[:through]
-
Associations::HasManyThroughAssociation
-
else
-
Associations::HasManyAssociation
-
end
-
when :has_one
-
if options[:through]
-
Associations::HasOneThroughAssociation
-
else
-
Associations::HasOneAssociation
-
end
-
end
-
end
-
-
1
def polymorphic?
-
options.key? :polymorphic
-
end
-
-
1
private
-
1
def derive_class_name
-
class_name = name.to_s.camelize
-
class_name = class_name.singularize if collection?
-
class_name
-
end
-
-
1
def derive_foreign_key
-
if belongs_to?
-
"#{name}_id"
-
elsif options[:as]
-
"#{options[:as]}_id"
-
else
-
active_record.name.foreign_key
-
end
-
end
-
-
1
def derive_join_table
-
[active_record.table_name, klass.table_name].sort.join("\0").gsub(/^(.*_)(.+)\0\1(.+)/, '\1\2_\3').gsub("\0", "_")
-
end
-
-
1
def primary_key(klass)
-
klass.primary_key || raise(UnknownPrimaryKey.new(klass))
-
end
-
end
-
-
# Holds all the meta-data about a :through association as it was specified
-
# in the Active Record class.
-
1
class ThroughReflection < AssociationReflection #:nodoc:
-
1
delegate :foreign_key, :foreign_type, :association_foreign_key,
-
:active_record_primary_key, :type, :to => :source_reflection
-
-
# Gets the source of the through reflection. It checks both a singularized
-
# and pluralized form for <tt>:belongs_to</tt> or <tt>:has_many</tt>.
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :taggings
-
# has_many :tags, through: :taggings
-
# end
-
#
-
1
def source_reflection
-
@source_reflection ||= source_reflection_names.collect { |name| through_reflection.klass.reflect_on_association(name) }.compact.first
-
end
-
-
# Returns the AssociationReflection object specified in the <tt>:through</tt> option
-
# of a HasManyThrough or HasOneThrough association.
-
#
-
# class Post < ActiveRecord::Base
-
# has_many :taggings
-
# has_many :tags, through: :taggings
-
# end
-
#
-
# tags_reflection = Post.reflect_on_association(:tags)
-
# taggings_reflection = tags_reflection.through_reflection
-
#
-
1
def through_reflection
-
@through_reflection ||= active_record.reflect_on_association(options[:through])
-
end
-
-
# Returns an array of reflections which are involved in this association. Each item in the
-
# array corresponds to a table which will be part of the query for this association.
-
#
-
# The chain is built by recursively calling #chain on the source reflection and the through
-
# reflection. The base case for the recursion is a normal association, which just returns
-
# [self] as its #chain.
-
1
def chain
-
@chain ||= begin
-
chain = source_reflection.chain + through_reflection.chain
-
chain[0] = self # Use self so we don't lose the information from :source_type
-
chain
-
end
-
end
-
-
# Consider the following example:
-
#
-
# class Person
-
# has_many :articles
-
# has_many :comment_tags, through: :articles
-
# end
-
#
-
# class Article
-
# has_many :comments
-
# has_many :comment_tags, through: :comments, source: :tags
-
# end
-
#
-
# class Comment
-
# has_many :tags
-
# end
-
#
-
# There may be scopes on Person.comment_tags, Article.comment_tags and/or Comment.tags,
-
# but only Comment.tags will be represented in the #chain. So this method creates an array
-
# of scopes corresponding to the chain.
-
1
def scope_chain
-
@scope_chain ||= begin
-
scope_chain = source_reflection.scope_chain.map(&:dup)
-
-
# Add to it the scope from this reflection (if any)
-
scope_chain.first << scope if scope
-
-
through_scope_chain = through_reflection.scope_chain
-
-
if options[:source_type]
-
through_scope_chain.first <<
-
through_reflection.klass.where(foreign_type => options[:source_type])
-
end
-
-
# Recursively fill out the rest of the array from the through reflection
-
scope_chain + through_scope_chain
-
end
-
end
-
-
# The macro used by the source association
-
1
def source_macro
-
source_reflection.source_macro
-
end
-
-
# A through association is nested if there would be more than one join table
-
1
def nested?
-
chain.length > 2 || through_reflection.macro == :has_and_belongs_to_many
-
end
-
-
# We want to use the klass from this reflection, rather than just delegate straight to
-
# the source_reflection, because the source_reflection may be polymorphic. We still
-
# need to respect the source_reflection's :primary_key option, though.
-
1
def association_primary_key(klass = nil)
-
# Get the "actual" source reflection if the immediate source reflection has a
-
# source reflection itself
-
source_reflection = self.source_reflection
-
while source_reflection.source_reflection
-
source_reflection = source_reflection.source_reflection
-
end
-
-
source_reflection.options[:primary_key] || primary_key(klass || self.klass)
-
end
-
-
# Gets an array of possible <tt>:through</tt> source reflection names:
-
#
-
# [:singularized, :pluralized]
-
#
-
1
def source_reflection_names
-
@source_reflection_names ||= (options[:source] ? [options[:source]] : [name.to_s.singularize, name]).collect { |n| n.to_sym }
-
end
-
-
1
def source_options
-
source_reflection.options
-
end
-
-
1
def through_options
-
through_reflection.options
-
end
-
-
1
def check_validity!
-
if through_reflection.nil?
-
raise HasManyThroughAssociationNotFoundError.new(active_record.name, self)
-
end
-
-
if through_reflection.options[:polymorphic]
-
raise HasManyThroughAssociationPolymorphicThroughError.new(active_record.name, self)
-
end
-
-
if source_reflection.nil?
-
raise HasManyThroughSourceAssociationNotFoundError.new(self)
-
end
-
-
if options[:source_type] && source_reflection.options[:polymorphic].nil?
-
raise HasManyThroughAssociationPointlessSourceTypeError.new(active_record.name, self, source_reflection)
-
end
-
-
if source_reflection.options[:polymorphic] && options[:source_type].nil?
-
raise HasManyThroughAssociationPolymorphicSourceError.new(active_record.name, self, source_reflection)
-
end
-
-
if macro == :has_one && through_reflection.collection?
-
raise HasOneThroughCantAssociateThroughCollection.new(active_record.name, self, through_reflection)
-
end
-
-
check_validity_of_inverse!
-
end
-
-
1
private
-
1
def derive_class_name
-
# get the class_name of the belongs_to association of the through reflection
-
options[:source_type] || source_reflection.class_name
-
end
-
end
-
end
-
end
-
# -*- coding: utf-8 -*-
-
-
1
module ActiveRecord
-
# = Active Record Relation
-
1
class Relation
-
1
JoinOperation = Struct.new(:relation, :join_class, :on)
-
-
1
MULTI_VALUE_METHODS = [:includes, :eager_load, :preload, :select, :group,
-
:order, :joins, :where, :having, :bind, :references,
-
:extending]
-
-
1
SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :from, :reordering,
-
:reverse_order, :uniq, :create_with]
-
-
1
VALUE_METHODS = MULTI_VALUE_METHODS + SINGLE_VALUE_METHODS
-
-
1
include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation
-
-
1
attr_reader :table, :klass, :loaded
-
1
attr_accessor :default_scoped
-
1
alias :model :klass
-
1
alias :loaded? :loaded
-
1
alias :default_scoped? :default_scoped
-
-
1
def initialize(klass, table, values = {})
-
@klass = klass
-
@table = table
-
@values = values
-
@implicit_readonly = nil
-
@loaded = false
-
@default_scoped = false
-
end
-
-
1
def insert(values)
-
primary_key_value = nil
-
-
if primary_key && Hash === values
-
primary_key_value = values[values.keys.find { |k|
-
k.name == primary_key
-
}]
-
-
if !primary_key_value && connection.prefetch_primary_key?(klass.table_name)
-
primary_key_value = connection.next_sequence_value(klass.sequence_name)
-
values[klass.arel_table[klass.primary_key]] = primary_key_value
-
end
-
end
-
-
im = arel.create_insert
-
im.into @table
-
-
conn = @klass.connection
-
-
substitutes = values.sort_by { |arel_attr,_| arel_attr.name }
-
binds = substitutes.map do |arel_attr, value|
-
[@klass.columns_hash[arel_attr.name], value]
-
end
-
-
substitutes.each_with_index do |tuple, i|
-
tuple[1] = conn.substitute_at(binds[i][0], i)
-
end
-
-
if values.empty? # empty insert
-
im.values = Arel.sql(connection.empty_insert_statement_value)
-
else
-
im.insert substitutes
-
end
-
-
conn.insert(
-
im,
-
'SQL',
-
primary_key,
-
primary_key_value,
-
nil,
-
binds)
-
end
-
-
# Initializes new record from relation while maintaining the current
-
# scope.
-
#
-
# Expects arguments in the same format as +Base.new+.
-
#
-
# users = User.where(name: 'DHH')
-
# user = users.new # => #<User id: nil, name: "DHH", created_at: nil, updated_at: nil>
-
#
-
# You can also pass a block to new with the new record as argument:
-
#
-
# user = users.new { |user| user.name = 'Oscar' }
-
# user.name # => Oscar
-
1
def new(*args, &block)
-
scoping { @klass.new(*args, &block) }
-
end
-
-
1
def initialize_copy(other)
-
# This method is a hot spot, so for now, use Hash[] to dup the hash.
-
# https://bugs.ruby-lang.org/issues/7166
-
@values = Hash[@values]
-
@values[:bind] = @values[:bind].dup if @values.key? :bind
-
reset
-
end
-
-
1
alias build new
-
-
# Tries to create a new record with the same scoped attributes
-
# defined in the relation. Returns the initialized object if validation fails.
-
#
-
# Expects arguments in the same format as +Base.create+.
-
#
-
# ==== Examples
-
# users = User.where(name: 'Oscar')
-
# users.create # #<User id: 3, name: "oscar", ...>
-
#
-
# users.create(name: 'fxn')
-
# users.create # #<User id: 4, name: "fxn", ...>
-
#
-
# users.create { |user| user.name = 'tenderlove' }
-
# # #<User id: 5, name: "tenderlove", ...>
-
#
-
# users.create(name: nil) # validation on name
-
# # #<User id: nil, name: nil, ...>
-
1
def create(*args, &block)
-
scoping { @klass.create(*args, &block) }
-
end
-
-
# Similar to #create, but calls +create!+ on the base class. Raises
-
# an exception if a validation error occurs.
-
#
-
# Expects arguments in the same format as <tt>Base.create!</tt>.
-
1
def create!(*args, &block)
-
scoping { @klass.create!(*args, &block) }
-
end
-
-
1
def first_or_create(attributes = nil, &block) # :nodoc:
-
first || create(attributes, &block)
-
end
-
-
1
def first_or_create!(attributes = nil, &block) # :nodoc:
-
first || create!(attributes, &block)
-
end
-
-
1
def first_or_initialize(attributes = nil, &block) # :nodoc:
-
first || new(attributes, &block)
-
end
-
-
# Finds the first record with the given attributes, or creates a record with the attributes
-
# if one is not found.
-
#
-
# ==== Examples
-
# # Find the first user named Penélope or create a new one.
-
# User.find_or_create_by(first_name: 'Penélope')
-
# # => <User id: 1, first_name: 'Penélope', last_name: nil>
-
#
-
# # Find the first user named Penélope or create a new one.
-
# # We already have one so the existing record will be returned.
-
# User.find_or_create_by(first_name: 'Penélope')
-
# # => <User id: 1, first_name: 'Penélope', last_name: nil>
-
#
-
# # Find the first user named Scarlett or create a new one with a particular last name.
-
# User.create_with(last_name: 'Johansson').find_or_create_by(first_name: 'Scarlett')
-
# # => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>
-
#
-
# # Find the first user named Scarlett or create a new one with a different last name.
-
# # We already have one so the existing record will be returned.
-
# User.find_or_create_by(first_name: 'Scarlett') do |user|
-
# user.last_name = "O'Hara"
-
# end
-
# # => <User id: 2, first_name: 'Scarlett', last_name: 'Johansson'>
-
1
def find_or_create_by(attributes, &block)
-
find_by(attributes) || create(attributes, &block)
-
end
-
-
# Like <tt>find_or_create_by</tt>, but calls <tt>create!</tt> so an exception is raised if the created record is invalid.
-
1
def find_or_create_by!(attributes, &block)
-
find_by(attributes) || create!(attributes, &block)
-
end
-
-
# Like <tt>find_or_create_by</tt>, but calls <tt>new</tt> instead of <tt>create</tt>.
-
1
def find_or_initialize_by(attributes, &block)
-
find_by(attributes) || new(attributes, &block)
-
end
-
-
# Runs EXPLAIN on the query or queries triggered by this relation and
-
# returns the result as a string. The string is formatted imitating the
-
# ones printed by the database shell.
-
#
-
# Note that this method actually runs the queries, since the results of some
-
# are needed by the next ones when eager loading is going on.
-
#
-
# Please see further details in the
-
# {Active Record Query Interface guide}[http://guides.rubyonrails.org/active_record_querying.html#running-explain].
-
1
def explain
-
_, queries = collecting_queries_for_explain { exec_queries }
-
exec_explain(queries)
-
end
-
-
# Converts relation objects to Array.
-
1
def to_a
-
load
-
@records
-
end
-
-
1
def as_json(options = nil) #:nodoc:
-
to_a.as_json(options)
-
end
-
-
# Returns size of the records.
-
1
def size
-
loaded? ? @records.length : count
-
end
-
-
# Returns true if there are no records.
-
1
def empty?
-
return @records.empty? if loaded?
-
-
c = count
-
c.respond_to?(:zero?) ? c.zero? : c.empty?
-
end
-
-
# Returns true if there are any records.
-
1
def any?
-
if block_given?
-
to_a.any? { |*block_args| yield(*block_args) }
-
else
-
!empty?
-
end
-
end
-
-
# Returns true if there is more than one record.
-
1
def many?
-
if block_given?
-
to_a.many? { |*block_args| yield(*block_args) }
-
else
-
limit_value ? to_a.many? : size > 1
-
end
-
end
-
-
# Scope all queries to the current scope.
-
#
-
# Comment.where(post_id: 1).scoping do
-
# Comment.first # SELECT * FROM comments WHERE post_id = 1
-
# end
-
#
-
# Please check unscoped if you want to remove all previous scopes (including
-
# the default_scope) during the execution of a block.
-
1
def scoping
-
previous, klass.current_scope = klass.current_scope, self
-
yield
-
ensure
-
klass.current_scope = previous
-
end
-
-
# Updates all records with details given if they match a set of conditions supplied, limits and order can
-
# also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the
-
# database. It does not instantiate the involved models and it does not trigger Active Record callbacks
-
# or validations.
-
#
-
# ==== Parameters
-
#
-
# * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
-
#
-
# ==== Examples
-
#
-
# # Update all customers with the given attributes
-
# Customer.update_all wants_email: true
-
#
-
# # Update all books with 'Rails' in their title
-
# Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')
-
#
-
# # Update all books that match conditions, but limit it to 5 ordered by date
-
# Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(author: 'David')
-
1
def update_all(updates)
-
raise ArgumentError, "Empty list of attributes to change" if updates.blank?
-
-
stmt = Arel::UpdateManager.new(arel.engine)
-
-
stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates))
-
stmt.table(table)
-
stmt.key = table[primary_key]
-
-
if joins_values.any?
-
@klass.connection.join_to_update(stmt, arel)
-
else
-
stmt.take(arel.limit)
-
stmt.order(*arel.orders)
-
stmt.wheres = arel.constraints
-
end
-
-
@klass.connection.update stmt, 'SQL', bind_values
-
end
-
-
# Updates an object (or multiple objects) and saves it to the database, if validations pass.
-
# The resulting object is returned whether the object was saved successfully to the database or not.
-
#
-
# ==== Parameters
-
#
-
# * +id+ - This should be the id or an array of ids to be updated.
-
# * +attributes+ - This should be a hash of attributes or an array of hashes.
-
#
-
# ==== Examples
-
#
-
# # Updates one record
-
# Person.update(15, user_name: 'Samuel', group: 'expert')
-
#
-
# # Updates multiple records
-
# people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
-
# Person.update(people.keys, people.values)
-
1
def update(id, attributes)
-
if id.is_a?(Array)
-
id.map.with_index { |one_id, idx| update(one_id, attributes[idx]) }
-
else
-
object = find(id)
-
object.update_attributes(attributes)
-
object
-
end
-
end
-
-
# Destroys the records matching +conditions+ by instantiating each
-
# record and calling its +destroy+ method. Each object's callbacks are
-
# executed (including <tt>:dependent</tt> association options and
-
# +before_destroy+/+after_destroy+ Observer methods). Returns the
-
# collection of objects that were destroyed; each will be frozen, to
-
# reflect that no changes should be made (since they can't be
-
# persisted).
-
#
-
# Note: Instantiation, callback execution, and deletion of each
-
# record can be time consuming when you're removing many records at
-
# once. It generates at least one SQL +DELETE+ query per record (or
-
# possibly more, to enforce your callbacks). If you want to delete many
-
# rows quickly, without concern for their associations or callbacks, use
-
# +delete_all+ instead.
-
#
-
# ==== Parameters
-
#
-
# * +conditions+ - A string, array, or hash that specifies which records
-
# to destroy. If omitted, all records are destroyed. See the
-
# Conditions section in the introduction to ActiveRecord::Base for
-
# more information.
-
#
-
# ==== Examples
-
#
-
# Person.destroy_all("last_login < '2004-04-04'")
-
# Person.destroy_all(status: "inactive")
-
# Person.where(age: 0..18).destroy_all
-
1
def destroy_all(conditions = nil)
-
if conditions
-
where(conditions).destroy_all
-
else
-
to_a.each {|object| object.destroy }.tap { reset }
-
end
-
end
-
-
# Destroy an object (or multiple objects) that has the given id. The object is instantiated first,
-
# therefore all callbacks and filters are fired off before the object is deleted. This method is
-
# less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run.
-
#
-
# This essentially finds the object (or multiple objects) with the given id, creates a new object
-
# from the attributes, and then calls destroy on it.
-
#
-
# ==== Parameters
-
#
-
# * +id+ - Can be either an Integer or an Array of Integers.
-
#
-
# ==== Examples
-
#
-
# # Destroy a single object
-
# Todo.destroy(1)
-
#
-
# # Destroy multiple objects
-
# todos = [1,2,3]
-
# Todo.destroy(todos)
-
1
def destroy(id)
-
if id.is_a?(Array)
-
id.map { |one_id| destroy(one_id) }
-
else
-
find(id).destroy
-
end
-
end
-
-
# Deletes the records matching +conditions+ without instantiating the records
-
# first, and hence not calling the +destroy+ method nor invoking callbacks. This
-
# is a single SQL DELETE statement that goes straight to the database, much more
-
# efficient than +destroy_all+. Be careful with relations though, in particular
-
# <tt>:dependent</tt> rules defined on associations are not honored. Returns the
-
# number of rows affected.
-
#
-
# Post.delete_all("person_id = 5 AND (category = 'Something' OR category = 'Else')")
-
# Post.delete_all(["person_id = ? AND (category = ? OR category = ?)", 5, 'Something', 'Else'])
-
# Post.where(person_id: 5).where(category: ['Something', 'Else']).delete_all
-
#
-
# Both calls delete the affected posts all at once with a single DELETE statement.
-
# If you need to destroy dependent associations or call your <tt>before_*</tt> or
-
# +after_destroy+ callbacks, use the +destroy_all+ method instead.
-
#
-
# If a limit scope is supplied, +delete_all+ raises an ActiveRecord error:
-
#
-
# Post.limit(100).delete_all
-
# # => ActiveRecord::ActiveRecordError: delete_all doesn't support limit scope
-
1
def delete_all(conditions = nil)
-
raise ActiveRecordError.new("delete_all doesn't support limit scope") if self.limit_value
-
-
if conditions
-
where(conditions).delete_all
-
else
-
stmt = Arel::DeleteManager.new(arel.engine)
-
stmt.from(table)
-
-
if joins_values.any?
-
@klass.connection.join_to_delete(stmt, arel, table[primary_key])
-
else
-
stmt.wheres = arel.constraints
-
end
-
-
affected = @klass.connection.delete(stmt, 'SQL', bind_values)
-
-
reset
-
affected
-
end
-
end
-
-
# Deletes the row with a primary key matching the +id+ argument, using a
-
# SQL +DELETE+ statement, and returns the number of rows deleted. Active
-
# Record objects are not instantiated, so the object's callbacks are not
-
# executed, including any <tt>:dependent</tt> association options or
-
# Observer methods.
-
#
-
# You can delete multiple rows at once by passing an Array of <tt>id</tt>s.
-
#
-
# Note: Although it is often much faster than the alternative,
-
# <tt>#destroy</tt>, skipping callbacks might bypass business logic in
-
# your application that ensures referential integrity or performs other
-
# essential jobs.
-
#
-
# ==== Examples
-
#
-
# # Delete a single row
-
# Todo.delete(1)
-
#
-
# # Delete multiple rows
-
# Todo.delete([2,3,4])
-
1
def delete(id_or_array)
-
where(primary_key => id_or_array).delete_all
-
end
-
-
# Causes the records to be loaded from the database if they have not
-
# been loaded already. You can use this if for some reason you need
-
# to explicitly load some records before actually using them. The
-
# return value is the relation itself, not the records.
-
#
-
# Post.where(published: true).load # => #<ActiveRecord::Relation>
-
1
def load
-
unless loaded?
-
# We monitor here the entire execution rather than individual SELECTs
-
# because from the point of view of the user fetching the records of a
-
# relation is a single unit of work. You want to know if this call takes
-
# too long, not if the individual queries take too long.
-
#
-
# It could be the case that none of the queries involved surpass the
-
# threshold, and at the same time the sum of them all does. The user
-
# should get a query plan logged in that case.
-
logging_query_plan { exec_queries }
-
end
-
-
self
-
end
-
-
# Forces reloading of relation.
-
1
def reload
-
reset
-
load
-
end
-
-
1
def reset
-
@first = @last = @to_sql = @order_clause = @scope_for_create = @arel = @loaded = nil
-
@should_eager_load = @join_dependency = nil
-
@records = []
-
self
-
end
-
-
# Returns sql statement for the relation.
-
#
-
# Users.where(name: 'Oscar').to_sql
-
# # => SELECT "users".* FROM "users" WHERE "users"."name" = 'Oscar'
-
1
def to_sql
-
@to_sql ||= klass.connection.to_sql(arel, bind_values.dup)
-
end
-
-
# Returns a hash of where conditions
-
#
-
# Users.where(name: 'Oscar').where_values_hash
-
# # => {:name=>"oscar"}
-
1
def where_values_hash
-
equalities = with_default_scope.where_values.grep(Arel::Nodes::Equality).find_all { |node|
-
node.left.relation.name == table_name
-
}
-
-
binds = Hash[bind_values.find_all(&:first).map { |column, v| [column.name, v] }]
-
-
Hash[equalities.map { |where|
-
name = where.left.name
-
[name, binds.fetch(name.to_s) { where.right }]
-
}]
-
end
-
-
1
def scope_for_create
-
@scope_for_create ||= where_values_hash.merge(create_with_value)
-
end
-
-
# Returns true if relation needs eager loading.
-
1
def eager_loading?
-
@should_eager_load ||=
-
eager_load_values.any? ||
-
includes_values.any? && (joined_includes_values.any? || references_eager_loaded_tables?)
-
end
-
-
# Joins that are also marked for preloading. In which case we should just eager load them.
-
# Note that this is a naive implementation because we could have strings and symbols which
-
# represent the same association, but that aren't matched by this. Also, we could have
-
# nested hashes which partially match, e.g. { a: :b } & { a: [:b, :c] }
-
1
def joined_includes_values
-
includes_values & joins_values
-
end
-
-
# Compares two relations for equality.
-
1
def ==(other)
-
case other
-
when Relation
-
other.to_sql == to_sql
-
when Array
-
to_a == other
-
end
-
end
-
-
1
def pretty_print(q)
-
q.pp(self.to_a)
-
end
-
-
1
def with_default_scope #:nodoc:
-
if default_scoped? && default_scope = klass.send(:build_default_scope)
-
default_scope = default_scope.merge(self)
-
default_scope.default_scoped = false
-
default_scope
-
else
-
self
-
end
-
end
-
-
# Returns true if relation is blank.
-
1
def blank?
-
to_a.blank?
-
end
-
-
1
def values
-
Hash[@values]
-
end
-
-
1
def inspect
-
entries = to_a.take([limit_value, 11].compact.min).map!(&:inspect)
-
entries[10] = '...' if entries.size == 11
-
-
"#<#{self.class.name} [#{entries.join(', ')}]>"
-
end
-
-
1
private
-
-
1
def exec_queries
-
default_scoped = with_default_scope
-
-
if default_scoped.equal?(self)
-
@records = eager_loading? ? find_with_associations : @klass.find_by_sql(arel, bind_values)
-
-
preload = preload_values
-
preload += includes_values unless eager_loading?
-
preload.each do |associations|
-
ActiveRecord::Associations::Preloader.new(@records, associations).run
-
end
-
-
# @readonly_value is true only if set explicitly. @implicit_readonly is true if there
-
# are JOINS and no explicit SELECT.
-
readonly = readonly_value.nil? ? @implicit_readonly : readonly_value
-
@records.each { |record| record.readonly! } if readonly
-
else
-
@records = default_scoped.to_a
-
end
-
-
@loaded = true
-
@records
-
end
-
-
1
def references_eager_loaded_tables?
-
joined_tables = arel.join_sources.map do |join|
-
if join.is_a?(Arel::Nodes::StringJoin)
-
tables_in_string(join.left)
-
else
-
[join.left.table_name, join.left.table_alias]
-
end
-
end
-
-
joined_tables += [table.name, table.table_alias]
-
-
# always convert table names to downcase as in Oracle quoted table names are in uppercase
-
joined_tables = joined_tables.flatten.compact.map { |t| t.downcase }.uniq
-
string_tables = tables_in_string(to_sql)
-
-
if (references_values - joined_tables).any?
-
true
-
elsif (string_tables - joined_tables).any?
-
ActiveSupport::Deprecation.warn(
-
"It looks like you are eager loading table(s) (one of: #{string_tables.join(', ')}) " \
-
"that are referenced in a string SQL snippet. For example: \n" \
-
"\n" \
-
" Post.includes(:comments).where(\"comments.title = 'foo'\")\n" \
-
"\n" \
-
"Currently, Active Record recognises the table in the string, and knows to JOIN the " \
-
"comments table to the query, rather than loading comments in a separate query. " \
-
"However, doing this without writing a full-blown SQL parser is inherently flawed. " \
-
"Since we don't want to write an SQL parser, we are removing this functionality. " \
-
"From now on, you must explicitly tell Active Record when you are referencing a table " \
-
"from a string:\n" \
-
"\n" \
-
" Post.includes(:comments).where(\"comments.title = 'foo'\").references(:comments)\n\n"
-
)
-
true
-
else
-
false
-
end
-
end
-
-
1
def tables_in_string(string)
-
return [] if string.blank?
-
# always convert table names to downcase as in Oracle quoted table names are in uppercase
-
# ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries
-
string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map{ |s| s.downcase }.uniq - ['raw_sql_']
-
end
-
end
-
end
-
-
1
module ActiveRecord
-
1
module Batches
-
# Looping through a collection of records from the database
-
# (using the +all+ method, for example) is very inefficient
-
# since it will try to instantiate all the objects at once.
-
#
-
# In that case, batch processing methods allow you to work
-
# with the records in batches, thereby greatly reducing memory consumption.
-
#
-
# The #find_each method uses #find_in_batches with a batch size of 1000 (or as
-
# specified by the +:batch_size+ option).
-
#
-
# Person.all.find_each do |person|
-
# person.do_awesome_stuff
-
# end
-
#
-
# Person.where("age > 21").find_each do |person|
-
# person.party_all_night!
-
# end
-
#
-
# You can also pass the +:start+ option to specify
-
# an offset to control the starting point.
-
1
def find_each(options = {})
-
find_in_batches(options) do |records|
-
records.each { |record| yield record }
-
end
-
end
-
-
# Yields each batch of records that was found by the find +options+ as
-
# an array. The size of each batch is set by the +:batch_size+
-
# option; the default is 1000.
-
#
-
# You can control the starting point for the batch processing by
-
# supplying the +:start+ option. This is especially useful if you
-
# want multiple workers dealing with the same processing queue. You can
-
# make worker 1 handle all the records between id 0 and 10,000 and
-
# worker 2 handle from 10,000 and beyond (by setting the +:start+
-
# option on that worker).
-
#
-
# It's not possible to set the order. That is automatically set to
-
# ascending on the primary key ("id ASC") to make the batch ordering
-
# work. This also means that this method only works with integer-based
-
# primary keys. You can't set the limit either, that's used to control
-
# the batch sizes.
-
#
-
# Person.where("age > 21").find_in_batches do |group|
-
# sleep(50) # Make sure it doesn't get too crowded in there!
-
# group.each { |person| person.party_all_night! }
-
# end
-
#
-
# # Let's process the next 2000 records
-
# Person.all.find_in_batches(start: 2000, batch_size: 2000) do |group|
-
# group.each { |person| person.party_all_night! }
-
# end
-
1
def find_in_batches(options = {})
-
options.assert_valid_keys(:start, :batch_size)
-
-
relation = self
-
-
unless arel.orders.blank? && arel.taken.blank?
-
ActiveRecord::Base.logger.warn("Scoped order and limit are ignored, it's forced to be batch order and batch size")
-
end
-
-
start = options.delete(:start)
-
batch_size = options.delete(:batch_size) || 1000
-
-
relation = relation.reorder(batch_order).limit(batch_size)
-
records = start ? relation.where(table[primary_key].gteq(start)).to_a : relation.to_a
-
-
while records.any?
-
records_size = records.size
-
primary_key_offset = records.last.id
-
-
yield records
-
-
break if records_size < batch_size
-
-
if primary_key_offset
-
records = relation.where(table[primary_key].gt(primary_key_offset)).to_a
-
else
-
raise "Primary key not included in the custom select clause"
-
end
-
end
-
end
-
-
1
private
-
-
1
def batch_order
-
"#{quoted_table_name}.#{quoted_primary_key} ASC"
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/try'
-
-
1
module ActiveRecord
-
1
module Calculations
-
# Count the records.
-
#
-
# Person.count
-
# # => the total count of all people
-
#
-
# Person.count(:age)
-
# # => returns the total count of all people whose age is present in database
-
#
-
# Person.count(:all)
-
# # => performs a COUNT(*) (:all is an alias for '*')
-
#
-
# Person.count(:age, distinct: true)
-
# # => counts the number of different age values
-
#
-
# Person.where("age > 26").count { |person| person.gender == 'female' }
-
# # => queries people where "age > 26" then count the loaded results filtering by gender
-
1
def count(column_name = nil, options = {})
-
if block_given?
-
self.to_a.count { |item| yield item }
-
else
-
column_name, options = nil, column_name if column_name.is_a?(Hash)
-
calculate(:count, column_name, options)
-
end
-
end
-
-
# Calculates the average value on a given column. Returns +nil+ if there's
-
# no row. See +calculate+ for examples with options.
-
#
-
# Person.average('age') # => 35.8
-
1
def average(column_name, options = {})
-
calculate(:average, column_name, options)
-
end
-
-
# Calculates the minimum value on a given column. The value is returned
-
# with the same data type of the column, or +nil+ if there's no row. See
-
# +calculate+ for examples with options.
-
#
-
# Person.minimum('age') # => 7
-
1
def minimum(column_name, options = {})
-
calculate(:minimum, column_name, options)
-
end
-
-
# Calculates the maximum value on a given column. The value is returned
-
# with the same data type of the column, or +nil+ if there's no row. See
-
# +calculate+ for examples with options.
-
#
-
# Person.maximum('age') # => 93
-
1
def maximum(column_name, options = {})
-
calculate(:maximum, column_name, options)
-
end
-
-
# Calculates the sum of values on a given column. The value is returned
-
# with the same data type of the column, 0 if there's no row. See
-
# +calculate+ for examples with options.
-
#
-
# Person.sum('age') # => 4562
-
# # => returns the total sum of all people's age
-
#
-
# Person.where('age > 100').sum { |person| person.age - 100 }
-
# # queries people where "age > 100" then perform a sum calculation with the block returns
-
1
def sum(*args)
-
if block_given?
-
self.to_a.sum(*args) { |item| yield item }
-
else
-
calculate(:sum, *args)
-
end
-
end
-
-
# This calculates aggregate values in the given column. Methods for count, sum, average,
-
# minimum, and maximum have been added as shortcuts.
-
#
-
# There are two basic forms of output:
-
#
-
# * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float
-
# for AVG, and the given column's type for everything else.
-
#
-
# * Grouped values: This returns an ordered hash of the values and groups them. It
-
# takes either a column name, or the name of a belongs_to association.
-
#
-
# values = Person.group('last_name').maximum(:age)
-
# puts values["Drake"]
-
# => 43
-
#
-
# drake = Family.find_by_last_name('Drake')
-
# values = Person.group(:family).maximum(:age) # Person belongs_to :family
-
# puts values[drake]
-
# => 43
-
#
-
# values.each do |family, max_age|
-
# ...
-
# end
-
#
-
# Examples:
-
# Person.calculate(:count, :all) # The same as Person.count
-
# Person.average(:age) # SELECT AVG(age) FROM people...
-
#
-
# # Selects the minimum age for any family without any minors
-
# Person.group(:last_name).having("min(age) > 17").minimum(:age)
-
#
-
# Person.sum("2 * age")
-
1
def calculate(operation, column_name, options = {})
-
relation = with_default_scope
-
-
if relation.equal?(self)
-
if has_include?(column_name)
-
construct_relation_for_association_calculations.calculate(operation, column_name, options)
-
else
-
perform_calculation(operation, column_name, options)
-
end
-
else
-
relation.calculate(operation, column_name, options)
-
end
-
rescue ThrowResult
-
0
-
end
-
-
# Use <tt>pluck</tt> as a shortcut to select a single attribute without
-
# loading a bunch of records just to grab one attribute you want.
-
#
-
# Person.pluck(:name)
-
#
-
# instead of
-
#
-
# Person.all.map(&:name)
-
#
-
# Pluck returns an <tt>Array</tt> of attribute values type-casted to match
-
# the plucked column name, if it can be deduced. Plucking an SQL fragment
-
# returns String values by default.
-
#
-
# Examples:
-
#
-
# Person.pluck(:id)
-
# # SELECT people.id FROM people
-
# # => [1, 2, 3]
-
#
-
# Person.pluck(:id, :name)
-
# # SELECT people.id, people.name FROM people
-
# # => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
-
#
-
# Person.uniq.pluck(:role)
-
# # SELECT DISTINCT role FROM people
-
# # => ['admin', 'member', 'guest']
-
#
-
# Person.where(:age => 21).limit(5).pluck(:id)
-
# # SELECT people.id FROM people WHERE people.age = 21 LIMIT 5
-
# # => [2, 3]
-
#
-
# Person.pluck('DATEDIFF(updated_at, created_at)')
-
# # SELECT DATEDIFF(updated_at, created_at) FROM people
-
# # => ['0', '27761', '173']
-
#
-
1
def pluck(*column_names)
-
column_names.map! do |column_name|
-
if column_name.is_a?(Symbol) && self.column_names.include?(column_name.to_s)
-
"#{connection.quote_table_name(table_name)}.#{connection.quote_column_name(column_name)}"
-
else
-
column_name
-
end
-
end
-
-
if has_include?(column_names.first)
-
construct_relation_for_association_calculations.pluck(*column_names)
-
else
-
result = klass.connection.select_all(select(column_names).arel, nil, bind_values)
-
columns = result.columns.map do |key|
-
klass.column_types.fetch(key) {
-
result.column_types.fetch(key) {
-
Class.new { def type_cast(v); v; end }.new
-
}
-
}
-
end
-
-
result = result.map do |attributes|
-
values = klass.initialize_attributes(attributes).values
-
-
columns.zip(values).map do |column, value|
-
column.type_cast(value)
-
end
-
end
-
columns.one? ? result.map!(&:first) : result
-
end
-
end
-
-
# Pluck all the ID's for the relation using the table's primary key
-
#
-
# Examples:
-
#
-
# Person.ids # SELECT people.id FROM people
-
# Person.joins(:companies).ids # SELECT people.id FROM people INNER JOIN companies ON companies.person_id = people.id
-
1
def ids
-
pluck primary_key
-
end
-
-
1
private
-
-
1
def has_include?(column_name)
-
eager_loading? || (includes_values.present? && (column_name || references_eager_loaded_tables?))
-
end
-
-
1
def perform_calculation(operation, column_name, options = {})
-
operation = operation.to_s.downcase
-
-
distinct = options[:distinct]
-
-
if operation == "count"
-
column_name ||= (select_for_count || :all)
-
-
unless arel.ast.grep(Arel::Nodes::OuterJoin).empty?
-
distinct = true
-
end
-
-
column_name = primary_key if column_name == :all && distinct
-
-
distinct = nil if column_name =~ /\s*DISTINCT\s+/i
-
end
-
-
if group_values.any?
-
execute_grouped_calculation(operation, column_name, distinct)
-
else
-
execute_simple_calculation(operation, column_name, distinct)
-
end
-
end
-
-
1
def aggregate_column(column_name)
-
if @klass.column_names.include?(column_name.to_s)
-
Arel::Attribute.new(@klass.unscoped.table, column_name)
-
else
-
Arel.sql(column_name == :all ? "*" : column_name.to_s)
-
end
-
end
-
-
1
def operation_over_aggregate_column(column, operation, distinct)
-
operation == 'count' ? column.count(distinct) : column.send(operation)
-
end
-
-
1
def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
-
# Postgresql doesn't like ORDER BY when there are no GROUP BY
-
relation = reorder(nil)
-
-
if operation == "count" && (relation.limit_value || relation.offset_value)
-
# Shortcut when limit is zero.
-
return 0 if relation.limit_value == 0
-
-
query_builder = build_count_subquery(relation, column_name, distinct)
-
else
-
column = aggregate_column(column_name)
-
-
select_value = operation_over_aggregate_column(column, operation, distinct)
-
-
relation.select_values = [select_value]
-
-
query_builder = relation.arel
-
end
-
-
result = @klass.connection.select_value(query_builder, nil, relation.bind_values)
-
type_cast_calculated_value(result, column_for(column_name), operation)
-
end
-
-
1
def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
-
group_attrs = group_values
-
-
if group_attrs.first.respond_to?(:to_sym)
-
association = @klass.reflect_on_association(group_attrs.first.to_sym)
-
associated = group_attrs.size == 1 && association && association.macro == :belongs_to # only count belongs_to associations
-
group_fields = Array(associated ? association.foreign_key : group_attrs)
-
else
-
group_fields = group_attrs
-
end
-
-
group_aliases = group_fields.map { |field| column_alias_for(field) }
-
group_columns = group_aliases.zip(group_fields).map { |aliaz,field|
-
[aliaz, column_for(field)]
-
}
-
-
group = @klass.connection.adapter_name == 'FrontBase' ? group_aliases : group_fields
-
-
if operation == 'count' && column_name == :all
-
aggregate_alias = 'count_all'
-
else
-
aggregate_alias = column_alias_for(operation, column_name)
-
end
-
-
select_values = [
-
operation_over_aggregate_column(
-
aggregate_column(column_name),
-
operation,
-
distinct).as(aggregate_alias)
-
]
-
select_values += select_values unless having_values.empty?
-
-
select_values.concat group_fields.zip(group_aliases).map { |field,aliaz|
-
if field.respond_to?(:as)
-
field.as(aliaz)
-
else
-
"#{field} AS #{aliaz}"
-
end
-
}
-
-
relation = except(:group).group(group)
-
relation.select_values = select_values
-
-
calculated_data = @klass.connection.select_all(relation, nil, bind_values)
-
-
if association
-
key_ids = calculated_data.collect { |row| row[group_aliases.first] }
-
key_records = association.klass.base_class.find(key_ids)
-
key_records = Hash[key_records.map { |r| [r.id, r] }]
-
end
-
-
Hash[calculated_data.map do |row|
-
key = group_columns.map { |aliaz, column|
-
type_cast_calculated_value(row[aliaz], column)
-
}
-
key = key.first if key.size == 1
-
key = key_records[key] if associated
-
[key, type_cast_calculated_value(row[aggregate_alias], column_for(column_name), operation)]
-
end]
-
end
-
-
# Converts the given keys to the value that the database adapter returns as
-
# a usable column name:
-
#
-
# column_alias_for("users.id") # => "users_id"
-
# column_alias_for("sum(id)") # => "sum_id"
-
# column_alias_for("count(distinct users.id)") # => "count_distinct_users_id"
-
# column_alias_for("count(*)") # => "count_all"
-
# column_alias_for("count", "id") # => "count_id"
-
1
def column_alias_for(*keys)
-
keys.map! {|k| k.respond_to?(:to_sql) ? k.to_sql : k}
-
table_name = keys.join(' ')
-
table_name.downcase!
-
table_name.gsub!(/\*/, 'all')
-
table_name.gsub!(/\W+/, ' ')
-
table_name.strip!
-
table_name.gsub!(/ +/, '_')
-
-
@klass.connection.table_alias_for(table_name)
-
end
-
-
1
def column_for(field)
-
field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split('.').last
-
@klass.columns_hash[field_name]
-
end
-
-
1
def type_cast_calculated_value(value, column, operation = nil)
-
case operation
-
when 'count' then value.to_i
-
when 'sum' then type_cast_using_column(value || 0, column)
-
when 'average' then value.respond_to?(:to_d) ? value.to_d : value
-
else type_cast_using_column(value, column)
-
end
-
end
-
-
1
def type_cast_using_column(value, column)
-
column ? column.type_cast(value) : value
-
end
-
-
1
def select_for_count
-
if select_values.present?
-
select = select_values.join(", ")
-
select if select !~ /[,*]/
-
end
-
end
-
-
1
def build_count_subquery(relation, column_name, distinct)
-
column_alias = Arel.sql('count_column')
-
subquery_alias = Arel.sql('subquery_for_count')
-
-
aliased_column = aggregate_column(column_name == :all ? 1 : column_name).as(column_alias)
-
relation.select_values = [aliased_column]
-
subquery = relation.arel.as(subquery_alias)
-
-
sm = Arel::SelectManager.new relation.engine
-
select_value = operation_over_aggregate_column(column_alias, 'count', distinct)
-
sm.project(select_value).from(subquery)
-
end
-
end
-
end
-
1
require 'thread'
-
-
1
module ActiveRecord
-
1
module Delegation # :nodoc:
-
# Set up common delegations for performance (avoids method_missing)
-
1
delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to_ary, :to => :to_a
-
1
delegate :table_name, :quoted_table_name, :primary_key, :quoted_primary_key,
-
:connection, :columns_hash, :auto_explain_threshold_in_seconds, :to => :klass
-
-
1
@@delegation_mutex = Mutex.new
-
-
1
def self.delegate_to_scoped_klass(method)
-
if method.to_s =~ /\A[a-zA-Z_]\w*[!?]?\z/
-
module_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{method}(*args, &block)
-
scoping { @klass.#{method}(*args, &block) }
-
end
-
RUBY
-
else
-
module_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{method}(*args, &block)
-
scoping { @klass.send(#{method.inspect}, *args, &block) }
-
end
-
RUBY
-
end
-
end
-
-
1
def respond_to?(method, include_private = false)
-
super || Array.method_defined?(method) ||
-
@klass.respond_to?(method, include_private) ||
-
arel.respond_to?(method, include_private)
-
end
-
-
1
protected
-
-
1
def method_missing(method, *args, &block)
-
if @klass.respond_to?(method)
-
@@delegation_mutex.synchronize do
-
unless ::ActiveRecord::Delegation.method_defined?(method)
-
::ActiveRecord::Delegation.delegate_to_scoped_klass(method)
-
end
-
end
-
-
scoping { @klass.send(method, *args, &block) }
-
elsif Array.method_defined?(method)
-
@@delegation_mutex.synchronize do
-
unless ::ActiveRecord::Delegation.method_defined?(method)
-
::ActiveRecord::Delegation.delegate method, :to => :to_a
-
end
-
end
-
-
to_a.send(method, *args, &block)
-
elsif arel.respond_to?(method)
-
@@delegation_mutex.synchronize do
-
unless ::ActiveRecord::Delegation.method_defined?(method)
-
::ActiveRecord::Delegation.delegate method, :to => :arel
-
end
-
end
-
-
arel.send(method, *args, &block)
-
else
-
super
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module FinderMethods
-
# Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]).
-
# If no record can be found for all of the listed ids, then RecordNotFound will be raised. If the primary key
-
# is an integer, find by id coerces its arguments using +to_i+.
-
#
-
# Person.find(1) # returns the object for ID = 1
-
# Person.find("1") # returns the object for ID = 1
-
# Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
-
# Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
-
# Person.find([1]) # returns an array for the object with ID = 1
-
# Person.where("administrator = 1").order("created_on DESC").find(1)
-
#
-
# Note that returned records may not be in the same order as the ids you
-
# provide since database rows are unordered. Give an explicit <tt>order</tt>
-
# to ensure the results are sorted.
-
#
-
# ==== Find with lock
-
#
-
# Example for find with a lock: Imagine two concurrent transactions:
-
# each will read <tt>person.visits == 2</tt>, add 1 to it, and save, resulting
-
# in two saves of <tt>person.visits = 3</tt>. By locking the row, the second
-
# transaction has to wait until the first is finished; we get the
-
# expected <tt>person.visits == 4</tt>.
-
#
-
# Person.transaction do
-
# person = Person.lock(true).find(1)
-
# person.visits += 1
-
# person.save!
-
# end
-
1
def find(*args)
-
if block_given?
-
to_a.find { |*block_args| yield(*block_args) }
-
else
-
find_with_ids(*args)
-
end
-
end
-
-
# Finds the first record matching the specified conditions. There
-
# is no implied ording so if order matters, you should specify it
-
# yourself.
-
#
-
# If no record is found, returns <tt>nil</tt>.
-
#
-
# Post.find_by name: 'Spartacus', rating: 4
-
# Post.find_by "published_at < ?", 2.weeks.ago
-
1
def find_by(*args)
-
where(*args).take
-
end
-
-
# Like <tt>find_by</tt>, except that if no record is found, raises
-
# an <tt>ActiveRecord::RecordNotFound</tt> error.
-
1
def find_by!(*args)
-
where(*args).take!
-
end
-
-
# Gives a record (or N records if a parameter is supplied) without any implied
-
# order. The order will depend on the database implementation.
-
# If an order is supplied it will be respected.
-
#
-
# Person.take # returns an object fetched by SELECT * FROM people
-
# Person.take(5) # returns 5 objects fetched by SELECT * FROM people LIMIT 5
-
# Person.where(["name LIKE '%?'", name]).take
-
1
def take(limit = nil)
-
limit ? limit(limit).to_a : find_take
-
end
-
-
# Same as +take+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found. Note that <tt>take!</tt> accepts no arguments.
-
1
def take!
-
take or raise RecordNotFound
-
end
-
-
# Find the first record (or first N records if a parameter is supplied).
-
# If no order is defined it will order by primary key.
-
#
-
# Person.first # returns the first object fetched by SELECT * FROM people
-
# Person.where(["user_name = ?", user_name]).first
-
# Person.where(["user_name = :u", { :u => user_name }]).first
-
# Person.order("created_on DESC").offset(5).first
-
# Person.first(3) # returns the first three objects fetched by SELECT * FROM people LIMIT 3
-
1
def first(limit = nil)
-
if limit
-
if order_values.empty? && primary_key
-
order(arel_table[primary_key].asc).limit(limit).to_a
-
else
-
limit(limit).to_a
-
end
-
else
-
find_first
-
end
-
end
-
-
# Same as +first+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found. Note that <tt>first!</tt> accepts no arguments.
-
1
def first!
-
first or raise RecordNotFound
-
end
-
-
# Find the last record (or last N records if a parameter is supplied).
-
# If no order is defined it will order by primary key.
-
#
-
# Person.last # returns the last object fetched by SELECT * FROM people
-
# Person.where(["user_name = ?", user_name]).last
-
# Person.order("created_on DESC").offset(5).last
-
# Person.last(3) # returns the last three objects fetched by SELECT * FROM people.
-
#
-
# Take note that in that last case, the results are sorted in ascending order:
-
#
-
# [#<Person id:2>, #<Person id:3>, #<Person id:4>]
-
#
-
# and not:
-
#
-
# [#<Person id:4>, #<Person id:3>, #<Person id:2>]
-
1
def last(limit = nil)
-
if limit
-
if order_values.empty? && primary_key
-
order(arel_table[primary_key].desc).limit(limit).reverse
-
else
-
to_a.last(limit)
-
end
-
else
-
find_last
-
end
-
end
-
-
# Same as +last+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
-
# is found. Note that <tt>last!</tt> accepts no arguments.
-
1
def last!
-
last or raise RecordNotFound
-
end
-
-
# Returns +true+ if a record exists in the table that matches the +id+ or
-
# conditions given, or +false+ otherwise. The argument can take six forms:
-
#
-
# * Integer - Finds the record with this primary key.
-
# * String - Finds the record with a primary key corresponding to this
-
# string (such as <tt>'5'</tt>).
-
# * Array - Finds the record that matches these +find+-style conditions
-
# (such as <tt>['color = ?', 'red']</tt>).
-
# * Hash - Finds the record that matches these +find+-style conditions
-
# (such as <tt>{color: 'red'}</tt>).
-
# * +false+ - Returns always +false+.
-
# * No args - Returns +false+ if the table is empty, +true+ otherwise.
-
#
-
# For more information about specifying conditions as a Hash or Array,
-
# see the Conditions section in the introduction to ActiveRecord::Base.
-
#
-
# Note: You can't pass in a condition as a string (like <tt>name =
-
# 'Jamie'</tt>), since it would be sanitized and then queried against
-
# the primary key column, like <tt>id = 'name = \'Jamie\''</tt>.
-
#
-
# Person.exists?(5)
-
# Person.exists?('5')
-
# Person.exists?(['name LIKE ?', "%#{query}%"])
-
# Person.exists?(name: 'David')
-
# Person.exists?(false)
-
# Person.exists?
-
1
def exists?(conditions = :none)
-
conditions = conditions.id if Base === conditions
-
return false if !conditions
-
-
join_dependency = construct_join_dependency_for_association_find
-
relation = construct_relation_for_association_find(join_dependency)
-
relation = relation.except(:select, :order).select("1 AS one").limit(1)
-
-
case conditions
-
when Array, Hash
-
relation = relation.where(conditions)
-
else
-
relation = relation.where(table[primary_key].eq(conditions)) if conditions != :none
-
end
-
-
connection.select_value(relation, "#{name} Exists", relation.bind_values)
-
rescue ThrowResult
-
false
-
end
-
-
1
protected
-
-
1
def find_with_associations
-
join_dependency = construct_join_dependency_for_association_find
-
relation = construct_relation_for_association_find(join_dependency)
-
rows = connection.select_all(relation, 'SQL', relation.bind_values.dup)
-
join_dependency.instantiate(rows)
-
rescue ThrowResult
-
[]
-
end
-
-
1
def construct_join_dependency_for_association_find
-
including = (eager_load_values + includes_values).uniq
-
ActiveRecord::Associations::JoinDependency.new(@klass, including, [])
-
end
-
-
1
def construct_relation_for_association_calculations
-
including = (eager_load_values + includes_values).uniq
-
join_dependency = ActiveRecord::Associations::JoinDependency.new(@klass, including, arel.froms.first)
-
relation = except(:includes, :eager_load, :preload)
-
apply_join_dependency(relation, join_dependency)
-
end
-
-
1
def construct_relation_for_association_find(join_dependency)
-
relation = except(:includes, :eager_load, :preload, :select).select(join_dependency.columns)
-
apply_join_dependency(relation, join_dependency)
-
end
-
-
1
def apply_join_dependency(relation, join_dependency)
-
join_dependency.join_associations.each do |association|
-
relation = association.join_relation(relation)
-
end
-
-
limitable_reflections = using_limitable_reflections?(join_dependency.reflections)
-
-
if !limitable_reflections && relation.limit_value
-
limited_id_condition = construct_limited_ids_condition(relation.except(:select))
-
relation = relation.where(limited_id_condition)
-
end
-
-
relation = relation.except(:limit, :offset) unless limitable_reflections
-
-
relation
-
end
-
-
1
def construct_limited_ids_condition(relation)
-
orders = relation.order_values.map { |val| val.presence }.compact
-
values = @klass.connection.distinct("#{quoted_table_name}.#{primary_key}", orders)
-
-
relation = relation.dup
-
-
ids_array = relation.select(values).collect {|row| row[primary_key]}
-
ids_array.empty? ? raise(ThrowResult) : table[primary_key].in(ids_array)
-
end
-
-
1
def find_with_ids(*ids)
-
expects_array = ids.first.kind_of?(Array)
-
return ids.first if expects_array && ids.first.empty?
-
-
ids = ids.flatten.compact.uniq
-
-
case ids.size
-
when 0
-
raise RecordNotFound, "Couldn't find #{@klass.name} without an ID"
-
when 1
-
result = find_one(ids.first)
-
expects_array ? [ result ] : result
-
else
-
find_some(ids)
-
end
-
end
-
-
1
def find_one(id)
-
id = id.id if ActiveRecord::Base === id
-
-
column = columns_hash[primary_key]
-
substitute = connection.substitute_at(column, bind_values.length)
-
relation = where(table[primary_key].eq(substitute))
-
relation.bind_values += [[column, id]]
-
record = relation.take
-
-
unless record
-
conditions = arel.where_sql
-
conditions = " [#{conditions}]" if conditions
-
raise RecordNotFound, "Couldn't find #{@klass.name} with #{primary_key}=#{id}#{conditions}"
-
end
-
-
record
-
end
-
-
1
def find_some(ids)
-
result = where(table[primary_key].in(ids)).to_a
-
-
expected_size =
-
if limit_value && ids.size > limit_value
-
limit_value
-
else
-
ids.size
-
end
-
-
# 11 ids with limit 3, offset 9 should give 2 results.
-
if offset_value && (ids.size - offset_value < expected_size)
-
expected_size = ids.size - offset_value
-
end
-
-
if result.size == expected_size
-
result
-
else
-
conditions = arel.where_sql
-
conditions = " [#{conditions}]" if conditions
-
-
error = "Couldn't find all #{@klass.name.pluralize} with IDs "
-
error << "(#{ids.join(", ")})#{conditions} (found #{result.size} results, but was looking for #{expected_size})"
-
raise RecordNotFound, error
-
end
-
end
-
-
1
def find_take
-
if loaded?
-
@records.first
-
else
-
@take ||= limit(1).to_a.first
-
end
-
end
-
-
1
def find_first
-
if loaded?
-
@records.first
-
else
-
@first ||=
-
if with_default_scope.order_values.empty? && primary_key
-
order(arel_table[primary_key].asc).limit(1).to_a.first
-
else
-
limit(1).to_a.first
-
end
-
end
-
end
-
-
1
def find_last
-
if loaded?
-
@records.last
-
else
-
@last ||=
-
if offset_value || limit_value
-
to_a.last
-
else
-
reverse_order.limit(1).to_a.first
-
end
-
end
-
end
-
-
1
def using_limitable_reflections?(reflections)
-
reflections.none? { |r| r.collection? }
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
-
1
module ActiveRecord
-
1
class Relation
-
1
class HashMerger # :nodoc:
-
1
attr_reader :relation, :hash
-
-
1
def initialize(relation, hash)
-
hash.assert_valid_keys(*Relation::VALUE_METHODS)
-
-
@relation = relation
-
@hash = hash
-
end
-
-
1
def merge
-
Merger.new(relation, other).merge
-
end
-
-
# Applying values to a relation has some side effects. E.g.
-
# interpolation might take place for where values. So we should
-
# build a relation to merge in rather than directly merging
-
# the values.
-
1
def other
-
other = Relation.new(relation.klass, relation.table)
-
hash.each { |k, v|
-
if k == :joins
-
if Hash === v
-
other.joins!(v)
-
else
-
other.joins!(*v)
-
end
-
else
-
other.send("#{k}!", v)
-
end
-
}
-
other
-
end
-
end
-
-
1
class Merger # :nodoc:
-
1
attr_reader :relation, :values
-
-
1
def initialize(relation, other)
-
if other.default_scoped? && other.klass != relation.klass
-
other = other.with_default_scope
-
end
-
-
@relation = relation
-
@values = other.values
-
end
-
-
1
NORMAL_VALUES = Relation::SINGLE_VALUE_METHODS +
-
Relation::MULTI_VALUE_METHODS -
-
[:where, :order, :bind, :reverse_order, :lock, :create_with, :reordering, :from] # :nodoc:
-
-
1
def normal_values
-
NORMAL_VALUES
-
end
-
-
1
def merge
-
normal_values.each do |name|
-
value = values[name]
-
relation.send("#{name}!", *value) unless value.blank?
-
end
-
-
merge_multi_values
-
merge_single_values
-
-
relation
-
end
-
-
1
private
-
-
1
def merge_multi_values
-
relation.where_values = merged_wheres
-
relation.bind_values = merged_binds
-
-
if values[:reordering]
-
# override any order specified in the original relation
-
relation.reorder! values[:order]
-
elsif values[:order]
-
# merge in order_values from r
-
relation.order! values[:order]
-
end
-
-
relation.extend(*values[:extending]) unless values[:extending].blank?
-
end
-
-
1
def merge_single_values
-
relation.from_value = values[:from] unless relation.from_value
-
relation.lock_value = values[:lock] unless relation.lock_value
-
relation.reverse_order_value = values[:reverse_order]
-
-
unless values[:create_with].blank?
-
relation.create_with_value = (relation.create_with_value || {}).merge(values[:create_with])
-
end
-
end
-
-
1
def merged_binds
-
if values[:bind]
-
(relation.bind_values + values[:bind]).uniq(&:first)
-
else
-
relation.bind_values
-
end
-
end
-
-
1
def merged_wheres
-
if values[:where]
-
merged_wheres = relation.where_values + values[:where]
-
-
unless relation.where_values.empty?
-
# Remove equalities with duplicated left-hand. Last one wins.
-
seen = {}
-
merged_wheres = merged_wheres.reverse.reject { |w|
-
nuke = false
-
if w.respond_to?(:operator) && w.operator == :==
-
nuke = seen[w.left]
-
seen[w.left] = true
-
end
-
nuke
-
}.reverse
-
end
-
-
merged_wheres
-
else
-
relation.where_values
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/array/wrap'
-
-
1
module ActiveRecord
-
1
module QueryMethods
-
1
extend ActiveSupport::Concern
-
-
1
Relation::MULTI_VALUE_METHODS.each do |name|
-
12
class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}_values # def select_values
-
@values[:#{name}] || [] # @values[:select] || []
-
end # end
-
#
-
def #{name}_values=(values) # def select_values=(values)
-
raise ImmutableRelation if @loaded # raise ImmutableRelation if @loaded
-
@values[:#{name}] = values # @values[:select] = values
-
end # end
-
CODE
-
end
-
-
1
(Relation::SINGLE_VALUE_METHODS - [:create_with]).each do |name|
-
8
class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}_value # def readonly_value
-
@values[:#{name}] # @values[:readonly]
-
end # end
-
CODE
-
end
-
-
1
Relation::SINGLE_VALUE_METHODS.each do |name|
-
9
class_eval <<-CODE, __FILE__, __LINE__ + 1
-
def #{name}_value=(value) # def readonly_value=(value)
-
raise ImmutableRelation if @loaded # raise ImmutableRelation if @loaded
-
@values[:#{name}] = value # @values[:readonly] = value
-
end # end
-
CODE
-
end
-
-
1
def create_with_value # :nodoc:
-
@values[:create_with] || {}
-
end
-
-
1
alias extensions extending_values
-
-
# Specify relationships to be included in the result set. For
-
# example:
-
#
-
# users = User.includes(:address)
-
# users.each do |user|
-
# user.address.city
-
# end
-
#
-
# allows you to access the +address+ attribute of the +User+ model without
-
# firing an additional query. This will often result in a
-
# performance improvement over a simple +join+.
-
#
-
# === conditions
-
#
-
# If you want to add conditions to your included models you'll have
-
# to explicitly reference them. For example:
-
#
-
# User.includes(:posts).where('posts.name = ?', 'example')
-
#
-
# Will throw an error, but this will work:
-
#
-
# User.includes(:posts).where('posts.name = ?', 'example').references(:posts)
-
1
def includes(*args)
-
args.empty? ? self : spawn.includes!(*args)
-
end
-
-
# Like #includes, but modifies the relation in place.
-
1
def includes!(*args)
-
args.reject! {|a| a.blank? }
-
-
self.includes_values = (includes_values + args).flatten.uniq
-
self
-
end
-
-
# Forces eager loading by performing a LEFT OUTER JOIN on +args+:
-
#
-
# User.eager_load(:posts)
-
# => SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, ...
-
# FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" =
-
# "users"."id"
-
1
def eager_load(*args)
-
args.blank? ? self : spawn.eager_load!(*args)
-
end
-
-
# Like #eager_load, but modifies relation in place.
-
1
def eager_load!(*args)
-
self.eager_load_values += args
-
self
-
end
-
-
# Allows preloading of +args+, in the same way that +includes+ does:
-
#
-
# User.preload(:posts)
-
# => SELECT "posts".* FROM "posts" WHERE "posts"."user_id" IN (1, 2, 3)
-
1
def preload(*args)
-
args.blank? ? self : spawn.preload!(*args)
-
end
-
-
# Like #preload, but modifies relation in place.
-
1
def preload!(*args)
-
self.preload_values += args
-
self
-
end
-
-
# Used to indicate that an association is referenced by an SQL string, and should
-
# therefore be JOINed in any query rather than loaded separately.
-
#
-
# User.includes(:posts).where("posts.name = 'foo'")
-
# # => Doesn't JOIN the posts table, resulting in an error.
-
#
-
# User.includes(:posts).where("posts.name = 'foo'").references(:posts)
-
# # => Query now knows the string references posts, so adds a JOIN
-
1
def references(*args)
-
args.blank? ? self : spawn.references!(*args)
-
end
-
-
# Like #references, but modifies relation in place.
-
1
def references!(*args)
-
args.flatten!
-
-
self.references_values = (references_values + args.map!(&:to_s)).uniq
-
self
-
end
-
-
# Works in two unique ways.
-
#
-
# First: takes a block so it can be used just like Array#select.
-
#
-
# Model.all.select { |m| m.field == value }
-
#
-
# This will build an array of objects from the database for the scope,
-
# converting them into an array and iterating through them using Array#select.
-
#
-
# Second: Modifies the SELECT statement for the query so that only certain
-
# fields are retrieved:
-
#
-
# Model.select(:field)
-
# # => [#<Model field:value>]
-
#
-
# Although in the above example it looks as though this method returns an
-
# array, it actually returns a relation object and can have other query
-
# methods appended to it, such as the other methods in ActiveRecord::QueryMethods.
-
#
-
# The argument to the method can also be an array of fields.
-
#
-
# Model.select(:field, :other_field, :and_one_more)
-
# # => [#<Model field: "value", other_field: "value", and_one_more: "value">]
-
#
-
# Accessing attributes of an object that do not have fields retrieved by a select
-
# will throw <tt>ActiveModel::MissingAttributeError</tt>:
-
#
-
# Model.select(:field).first.other_field
-
# # => ActiveModel::MissingAttributeError: missing attribute: other_field
-
1
def select(*fields)
-
if block_given?
-
to_a.select { |*block_args| yield(*block_args) }
-
else
-
raise ArgumentError, 'Call this with at least one field' if fields.empty?
-
spawn.select!(*fields)
-
end
-
end
-
-
# Like #select, but modifies relation in place.
-
1
def select!(*fields)
-
self.select_values += fields.flatten
-
self
-
end
-
-
# Allows to specify a group attribute:
-
#
-
# User.group(:name)
-
# => SELECT "users".* FROM "users" GROUP BY name
-
#
-
# Returns an array with distinct records based on the +group+ attribute:
-
#
-
# User.select([:id, :name])
-
# => [#<User id: 1, name: "Oscar">, #<User id: 2, name: "Oscar">, #<User id: 3, name: "Foo">
-
#
-
# User.group(:name)
-
# => [#<User id: 3, name: "Foo", ...>, #<User id: 2, name: "Oscar", ...>]
-
1
def group(*args)
-
args.blank? ? self : spawn.group!(*args)
-
end
-
-
# Like #group, but modifies relation in place.
-
1
def group!(*args)
-
args.flatten!
-
-
self.group_values += args
-
self
-
end
-
-
# Allows to specify an order attribute:
-
#
-
# User.order('name')
-
# => SELECT "users".* FROM "users" ORDER BY name
-
#
-
# User.order('name DESC')
-
# => SELECT "users".* FROM "users" ORDER BY name DESC
-
#
-
# User.order('name DESC, email')
-
# => SELECT "users".* FROM "users" ORDER BY name DESC, email
-
#
-
# User.order(:name)
-
# => SELECT "users".* FROM "users" ORDER BY "users"."name" ASC
-
#
-
# User.order(email: :desc)
-
# => SELECT "users".* FROM "users" ORDER BY "users"."email" DESC
-
#
-
# User.order(:name, email: :desc)
-
# => SELECT "users".* FROM "users" ORDER BY "users"."name" ASC, "users"."email" DESC
-
1
def order(*args)
-
args.blank? ? self : spawn.order!(*args)
-
end
-
-
# Like #order, but modifies relation in place.
-
1
def order!(*args)
-
args.flatten!
-
validate_order_args args
-
-
references = args.reject { |arg| Arel::Node === arg }
-
references.map! { |arg| arg =~ /^([a-zA-Z]\w*)\.(\w+)/ && $1 }.compact!
-
references!(references) if references.any?
-
-
self.order_values = args + self.order_values
-
self
-
end
-
-
# Replaces any existing order defined on the relation with the specified order.
-
#
-
# User.order('email DESC').reorder('id ASC') # generated SQL has 'ORDER BY id ASC'
-
#
-
# Subsequent calls to order on the same relation will be appended. For example:
-
#
-
# User.order('email DESC').reorder('id ASC').order('name ASC')
-
#
-
# generates a query with 'ORDER BY name ASC, id ASC'.
-
1
def reorder(*args)
-
args.blank? ? self : spawn.reorder!(*args)
-
end
-
-
# Like #reorder, but modifies relation in place.
-
1
def reorder!(*args)
-
args.flatten!
-
validate_order_args args
-
-
self.reordering_value = true
-
self.order_values = args
-
self
-
end
-
-
# Performs a joins on +args+:
-
#
-
# User.joins(:posts)
-
# => SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
-
1
def joins(*args)
-
args.compact.blank? ? self : spawn.joins!(*args.flatten)
-
end
-
-
# Like #joins, but modifies relation in place.
-
1
def joins!(*args)
-
self.joins_values += args
-
self
-
end
-
-
1
def bind(value)
-
spawn.bind!(value)
-
end
-
-
1
def bind!(value)
-
self.bind_values += [value]
-
self
-
end
-
-
# Returns a new relation, which is the result of filtering the current relation
-
# according to the conditions in the arguments.
-
#
-
# #where accepts conditions in one of several formats. In the examples below, the resulting
-
# SQL is given as an illustration; the actual query generated may be different depending
-
# on the database adapter.
-
#
-
# === string
-
#
-
# A single string, without additional arguments, is passed to the query
-
# constructor as a SQL fragment, and used in the where clause of the query.
-
#
-
# Client.where("orders_count = '2'")
-
# # SELECT * from clients where orders_count = '2';
-
#
-
# Note that building your own string from user input may expose your application
-
# to injection attacks if not done properly. As an alternative, it is recommended
-
# to use one of the following methods.
-
#
-
# === array
-
#
-
# If an array is passed, then the first element of the array is treated as a template, and
-
# the remaining elements are inserted into the template to generate the condition.
-
# Active Record takes care of building the query to avoid injection attacks, and will
-
# convert from the ruby type to the database type where needed. Elements are inserted
-
# into the string in the order in which they appear.
-
#
-
# User.where(["name = ? and email = ?", "Joe", "joe@example.com"])
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
-
#
-
# Alternatively, you can use named placeholders in the template, and pass a hash as the
-
# second element of the array. The names in the template are replaced with the corresponding
-
# values from the hash.
-
#
-
# User.where(["name = :name and email = :email", { name: "Joe", email: "joe@example.com" }])
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
-
#
-
# This can make for more readable code in complex queries.
-
#
-
# Lastly, you can use sprintf-style % escapes in the template. This works slightly differently
-
# than the previous methods; you are responsible for ensuring that the values in the template
-
# are properly quoted. The values are passed to the connector for quoting, but the caller
-
# is responsible for ensuring they are enclosed in quotes in the resulting SQL. After quoting,
-
# the values are inserted using the same escapes as the Ruby core method <tt>Kernel::sprintf</tt>.
-
#
-
# User.where(["name = '%s' and email = '%s'", "Joe", "joe@example.com"])
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
-
#
-
# If #where is called with multiple arguments, these are treated as if they were passed as
-
# the elements of a single array.
-
#
-
# User.where("name = :name and email = :email", { name: "Joe", email: "joe@example.com" })
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com';
-
#
-
# When using strings to specify conditions, you can use any operator available from
-
# the database. While this provides the most flexibility, you can also unintentionally introduce
-
# dependencies on the underlying database. If your code is intended for general consumption,
-
# test with multiple database backends.
-
#
-
# === hash
-
#
-
# #where will also accept a hash condition, in which the keys are fields and the values
-
# are values to be searched for.
-
#
-
# Fields can be symbols or strings. Values can be single values, arrays, or ranges.
-
#
-
# User.where({ name: "Joe", email: "joe@example.com" })
-
# # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com'
-
#
-
# User.where({ name: ["Alice", "Bob"]})
-
# # SELECT * FROM users WHERE name IN ('Alice', 'Bob')
-
#
-
# User.where({ created_at: (Time.now.midnight - 1.day)..Time.now.midnight })
-
# # SELECT * FROM users WHERE (created_at BETWEEN '2012-06-09 07:00:00.000000' AND '2012-06-10 07:00:00.000000')
-
#
-
# In the case of a belongs_to relationship, an association key can be used
-
# to specify the model if an ActiveRecord object is used as the value.
-
#
-
# author = Author.find(1)
-
#
-
# # The following queries will be equivalent:
-
# Post.where(:author => author)
-
# Post.where(:author_id => author)
-
#
-
# This also works with polymorphic belongs_to relationships:
-
#
-
# treasure = Treasure.create(:name => 'gold coins')
-
# treasure.price_estimates << PriceEstimate.create(:price => 125)
-
#
-
# # The following queries will be equivalent:
-
# PriceEstimate.where(:estimate_of => treasure)
-
# PriceEstimate.where(:estimate_of_type => 'Treasure', :estimate_of_id => treasure)
-
#
-
# === Joins
-
#
-
# If the relation is the result of a join, you may create a condition which uses any of the
-
# tables in the join. For string and array conditions, use the table name in the condition.
-
#
-
# User.joins(:posts).where("posts.created_at < ?", Time.now)
-
#
-
# For hash conditions, you can either use the table name in the key, or use a sub-hash.
-
#
-
# User.joins(:posts).where({ "posts.published" => true })
-
# User.joins(:posts).where({ :posts => { :published => true } })
-
#
-
# === empty condition
-
#
-
# If the condition returns true for blank?, then where is a no-op and returns the current relation.
-
1
def where(opts, *rest)
-
opts.blank? ? self : spawn.where!(opts, *rest)
-
end
-
-
# #where! is identical to #where, except that instead of returning a new relation, it adds
-
# the condition to the existing relation.
-
1
def where!(opts, *rest)
-
references!(PredicateBuilder.references(opts)) if Hash === opts
-
-
self.where_values += build_where(opts, rest)
-
self
-
end
-
-
# Allows to specify a HAVING clause. Note that you can't use HAVING
-
# without also specifying a GROUP clause.
-
#
-
# Order.having('SUM(price) > 30').group('user_id')
-
1
def having(opts, *rest)
-
opts.blank? ? self : spawn.having!(opts, *rest)
-
end
-
-
# Like #having, but modifies relation in place.
-
1
def having!(opts, *rest)
-
references!(PredicateBuilder.references(opts)) if Hash === opts
-
-
self.having_values += build_where(opts, rest)
-
self
-
end
-
-
# Specifies a limit for the number of records to retrieve.
-
#
-
# User.limit(10) # generated SQL has 'LIMIT 10'
-
#
-
# User.limit(10).limit(20) # generated SQL has 'LIMIT 20'
-
1
def limit(value)
-
spawn.limit!(value)
-
end
-
-
# Like #limit, but modifies relation in place.
-
1
def limit!(value)
-
self.limit_value = value
-
self
-
end
-
-
# Specifies the number of rows to skip before returning rows.
-
#
-
# User.offset(10) # generated SQL has "OFFSET 10"
-
#
-
# Should be used with order.
-
#
-
# User.offset(10).order("name ASC")
-
1
def offset(value)
-
spawn.offset!(value)
-
end
-
-
# Like #offset, but modifies relation in place.
-
1
def offset!(value)
-
self.offset_value = value
-
self
-
end
-
-
# Specifies locking settings (default to +true+). For more information
-
# on locking, please see +ActiveRecord::Locking+.
-
1
def lock(locks = true)
-
spawn.lock!(locks)
-
end
-
-
# Like #lock, but modifies relation in place.
-
1
def lock!(locks = true)
-
case locks
-
when String, TrueClass, NilClass
-
self.lock_value = locks || true
-
else
-
self.lock_value = false
-
end
-
-
self
-
end
-
-
# Returns a chainable relation with zero records, specifically an
-
# instance of the <tt>ActiveRecord::NullRelation</tt> class.
-
#
-
# The returned <tt>ActiveRecord::NullRelation</tt> inherits from Relation and implements the
-
# Null Object pattern. It is an object with defined null behavior and always returns an empty
-
# array of records without quering the database.
-
#
-
# Any subsequent condition chained to the returned relation will continue
-
# generating an empty relation and will not fire any query to the database.
-
#
-
# Used in cases where a method or scope could return zero records but the
-
# result needs to be chainable.
-
#
-
# For example:
-
#
-
# @posts = current_user.visible_posts.where(:name => params[:name])
-
# # => the visible_posts method is expected to return a chainable Relation
-
#
-
# def visible_posts
-
# case role
-
# when 'Country Manager'
-
# Post.where(:country => country)
-
# when 'Reviewer'
-
# Post.published
-
# when 'Bad User'
-
# Post.none # => returning [] instead breaks the previous code
-
# end
-
# end
-
#
-
1
def none
-
extending(NullRelation)
-
end
-
-
# Like #none, but modifies relation in place.
-
1
def none!
-
extending!(NullRelation)
-
end
-
-
# Sets readonly attributes for the returned relation. If value is
-
# true (default), attempting to update a record will result in an error.
-
#
-
# users = User.readonly
-
# users.first.save
-
# => ActiveRecord::ReadOnlyRecord: ActiveRecord::ReadOnlyRecord
-
1
def readonly(value = true)
-
spawn.readonly!(value)
-
end
-
-
# Like #readonly, but modifies relation in place.
-
1
def readonly!(value = true)
-
self.readonly_value = value
-
self
-
end
-
-
# Sets attributes to be used when creating new records from a
-
# relation object.
-
#
-
# users = User.where(name: 'Oscar')
-
# users.new.name # => 'Oscar'
-
#
-
# users = users.create_with(name: 'DHH')
-
# users.new.name # => 'DHH'
-
#
-
# You can pass +nil+ to +create_with+ to reset attributes:
-
#
-
# users = users.create_with(nil)
-
# users.new.name # => 'Oscar'
-
1
def create_with(value)
-
spawn.create_with!(value)
-
end
-
-
# Like #create_with but modifies the relation in place. Raises
-
# +ImmutableRelation+ if the relation has already been loaded.
-
#
-
# users = User.all.create_with!(name: 'Oscar')
-
# users.new.name # => 'Oscar'
-
1
def create_with!(value)
-
self.create_with_value = value ? create_with_value.merge(value) : {}
-
self
-
end
-
-
# Specifies table from which the records will be fetched. For example:
-
#
-
# Topic.select('title').from('posts')
-
# #=> SELECT title FROM posts
-
#
-
# Can accept other relation objects. For example:
-
#
-
# Topic.select('title').from(Topic.approved)
-
# # => SELECT title FROM (SELECT * FROM topics WHERE approved = 't') subquery
-
#
-
# Topic.select('a.title').from(Topic.approved, :a)
-
# # => SELECT a.title FROM (SELECT * FROM topics WHERE approved = 't') a
-
#
-
1
def from(value, subquery_name = nil)
-
spawn.from!(value, subquery_name)
-
end
-
-
# Like #from, but modifies relation in place.
-
1
def from!(value, subquery_name = nil)
-
self.from_value = [value, subquery_name]
-
self
-
end
-
-
# Specifies whether the records should be unique or not. For example:
-
#
-
# User.select(:name)
-
# # => Might return two records with the same name
-
#
-
# User.select(:name).uniq
-
# # => Returns 1 record per unique name
-
#
-
# User.select(:name).uniq.uniq(false)
-
# # => You can also remove the uniqueness
-
1
def uniq(value = true)
-
spawn.uniq!(value)
-
end
-
-
# Like #uniq, but modifies relation in place.
-
1
def uniq!(value = true)
-
self.uniq_value = value
-
self
-
end
-
-
# Used to extend a scope with additional methods, either through
-
# a module or through a block provided.
-
#
-
# The object returned is a relation, which can be further extended.
-
#
-
# === Using a module
-
#
-
# module Pagination
-
# def page(number)
-
# # pagination code goes here
-
# end
-
# end
-
#
-
# scope = Model.all.extending(Pagination)
-
# scope.page(params[:page])
-
#
-
# You can also pass a list of modules:
-
#
-
# scope = Model.all.extending(Pagination, SomethingElse)
-
#
-
# === Using a block
-
#
-
# scope = Model.all.extending do
-
# def page(number)
-
# # pagination code goes here
-
# end
-
# end
-
# scope.page(params[:page])
-
#
-
# You can also use a block and a module list:
-
#
-
# scope = Model.all.extending(Pagination) do
-
# def per_page(number)
-
# # pagination code goes here
-
# end
-
# end
-
1
def extending(*modules, &block)
-
if modules.any? || block
-
spawn.extending!(*modules, &block)
-
else
-
self
-
end
-
end
-
-
# Like #extending, but modifies relation in place.
-
1
def extending!(*modules, &block)
-
modules << Module.new(&block) if block_given?
-
-
self.extending_values += modules.flatten
-
extend(*extending_values) if extending_values.any?
-
-
self
-
end
-
-
# Reverse the existing order clause on the relation.
-
#
-
# User.order('name ASC').reverse_order # generated SQL has 'ORDER BY name DESC'
-
1
def reverse_order
-
spawn.reverse_order!
-
end
-
-
# Like #reverse_order, but modifies relation in place.
-
1
def reverse_order!
-
self.reverse_order_value = !reverse_order_value
-
self
-
end
-
-
# Returns the Arel object associated with the relation.
-
1
def arel
-
@arel ||= with_default_scope.build_arel
-
end
-
-
# Like #arel, but ignores the default scope of the model.
-
1
def build_arel
-
arel = Arel::SelectManager.new(table.engine, table)
-
-
build_joins(arel, joins_values) unless joins_values.empty?
-
-
collapse_wheres(arel, (where_values - ['']).uniq)
-
-
arel.having(*having_values.uniq.reject{|h| h.blank?}) unless having_values.empty?
-
-
arel.take(connection.sanitize_limit(limit_value)) if limit_value
-
arel.skip(offset_value.to_i) if offset_value
-
-
arel.group(*group_values.uniq.reject{|g| g.blank?}) unless group_values.empty?
-
-
build_order(arel)
-
-
build_select(arel, select_values.uniq)
-
-
arel.distinct(uniq_value)
-
arel.from(build_from) if from_value
-
arel.lock(lock_value) if lock_value
-
-
arel
-
end
-
-
1
private
-
-
1
def custom_join_ast(table, joins)
-
joins = joins.reject { |join| join.blank? }
-
-
return [] if joins.empty?
-
-
@implicit_readonly = true
-
-
joins.map do |join|
-
case join
-
when Array
-
join = Arel.sql(join.join(' ')) if array_of_strings?(join)
-
when String
-
join = Arel.sql(join)
-
end
-
table.create_string_join(join)
-
end
-
end
-
-
1
def collapse_wheres(arel, wheres)
-
equalities = wheres.grep(Arel::Nodes::Equality)
-
-
arel.where(Arel::Nodes::And.new(equalities)) unless equalities.empty?
-
-
(wheres - equalities).each do |where|
-
where = Arel.sql(where) if String === where
-
arel.where(Arel::Nodes::Grouping.new(where))
-
end
-
end
-
-
1
def build_where(opts, other = [])
-
case opts
-
when String, Array
-
[@klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))]
-
when Hash
-
attributes = @klass.send(:expand_hash_conditions_for_aggregates, opts)
-
PredicateBuilder.build_from_hash(klass, attributes, table)
-
else
-
[opts]
-
end
-
end
-
-
1
def build_from
-
opts, name = from_value
-
case opts
-
when Relation
-
name ||= 'subquery'
-
opts.arel.as(name.to_s)
-
else
-
opts
-
end
-
end
-
-
1
def build_joins(manager, joins)
-
buckets = joins.group_by do |join|
-
case join
-
when String
-
:string_join
-
when Hash, Symbol, Array
-
:association_join
-
when ActiveRecord::Associations::JoinDependency::JoinAssociation
-
:stashed_join
-
when Arel::Nodes::Join
-
:join_node
-
else
-
raise 'unknown class: %s' % join.class.name
-
end
-
end
-
-
association_joins = buckets[:association_join] || []
-
stashed_association_joins = buckets[:stashed_join] || []
-
join_nodes = (buckets[:join_node] || []).uniq
-
string_joins = (buckets[:string_join] || []).map { |x|
-
x.strip
-
}.uniq
-
-
join_list = join_nodes + custom_join_ast(manager, string_joins)
-
-
join_dependency = ActiveRecord::Associations::JoinDependency.new(
-
@klass,
-
association_joins,
-
join_list
-
)
-
-
join_dependency.graft(*stashed_association_joins)
-
-
@implicit_readonly = true unless association_joins.empty? && stashed_association_joins.empty?
-
-
# FIXME: refactor this to build an AST
-
join_dependency.join_associations.each do |association|
-
association.join_to(manager)
-
end
-
-
manager.join_sources.concat join_list
-
-
manager
-
end
-
-
1
def build_select(arel, selects)
-
unless selects.empty?
-
@implicit_readonly = false
-
arel.project(*selects)
-
else
-
arel.project(@klass.arel_table[Arel.star])
-
end
-
end
-
-
1
def reverse_sql_order(order_query)
-
order_query = ["#{quoted_table_name}.#{quoted_primary_key} ASC"] if order_query.empty?
-
-
order_query.flat_map do |o|
-
case o
-
when Arel::Nodes::Ordering
-
o.reverse
-
when String
-
o.to_s.split(',').collect do |s|
-
s.strip!
-
s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC')
-
end
-
when Symbol
-
{ o => :desc }
-
when Hash
-
o.each_with_object({}) do |(field, dir), memo|
-
memo[field] = (dir == :asc ? :desc : :asc )
-
end
-
else
-
o
-
end
-
end
-
end
-
-
1
def array_of_strings?(o)
-
o.is_a?(Array) && o.all?{|obj| obj.is_a?(String)}
-
end
-
-
1
def build_order(arel)
-
orders = order_values
-
orders = reverse_sql_order(orders) if reverse_order_value
-
-
orders = orders.uniq.reject(&:blank?).flat_map do |order|
-
case order
-
when Symbol
-
table[order].asc
-
when Hash
-
order.map { |field, dir| table[field].send(dir) }
-
else
-
order
-
end
-
end
-
-
arel.order(*orders) unless orders.empty?
-
end
-
-
1
def validate_order_args(args)
-
args.select { |a| Hash === a }.each do |h|
-
unless (h.values - [:asc, :desc]).empty?
-
raise ArgumentError, 'Direction should be :asc or :desc'
-
end
-
end
-
end
-
-
end
-
end
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_record/relation/merger'
-
-
1
module ActiveRecord
-
1
module SpawnMethods
-
-
# This is overridden by Associations::CollectionProxy
-
1
def spawn #:nodoc:
-
clone
-
end
-
-
# Merges in the conditions from <tt>other</tt>, if <tt>other</tt> is an <tt>ActiveRecord::Relation</tt>.
-
# Returns an array representing the intersection of the resulting records with <tt>other</tt>, if <tt>other</tt> is an array.
-
#
-
# ==== Examples
-
#
-
# Post.where(:published => true).joins(:comments).merge( Comment.where(:spam => false) )
-
# # Performs a single join query with both where conditions.
-
#
-
# recent_posts = Post.order('created_at DESC').first(5)
-
# Post.where(:published => true).merge(recent_posts)
-
# # Returns the intersection of all published posts with the 5 most recently created posts.
-
# # (This is just an example. You'd probably want to do this with a single query!)
-
#
-
# Procs will be evaluated by merge:
-
#
-
# Post.where(published: true).merge(-> { joins(:comments) })
-
# # => Post.where(published: true).joins(:comments)
-
#
-
# This is mainly intended for sharing common conditions between multiple associations.
-
#
-
1
def merge(other)
-
if other.is_a?(Array)
-
to_a & other
-
elsif other
-
spawn.merge!(other)
-
else
-
self
-
end
-
end
-
-
# Like #merge, but applies changes in place.
-
1
def merge!(other)
-
if !other.is_a?(Relation) && other.respond_to?(:to_proc)
-
instance_exec(&other)
-
else
-
klass = other.is_a?(Hash) ? Relation::HashMerger : Relation::Merger
-
klass.new(self, other).merge
-
end
-
end
-
-
# Removes from the query the condition(s) specified in +skips+.
-
#
-
# Example:
-
#
-
# Post.order('id asc').except(:order) # discards the order condition
-
# Post.where('id > 10').order('id asc').except(:where) # discards the where condition but keeps the order
-
#
-
1
def except(*skips)
-
result = Relation.new(klass, table, values.except(*skips))
-
result.default_scoped = default_scoped
-
result.extend(*extending_values) if extending_values.any?
-
result
-
end
-
-
# Removes any condition from the query other than the one(s) specified in +onlies+.
-
#
-
# Example:
-
#
-
# Post.order('id asc').only(:where) # discards the order condition
-
# Post.order('id asc').only(:where, :order) # uses the specified order
-
#
-
1
def only(*onlies)
-
result = Relation.new(klass, table, values.slice(*onlies))
-
result.default_scoped = default_scoped
-
result.extend(*extending_values) if extending_values.any?
-
result
-
end
-
-
end
-
end
-
1
module ActiveRecord
-
1
module Sanitization
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
1
def quote_value(value, column = nil) #:nodoc:
-
connection.quote(value,column)
-
end
-
-
# Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>.
-
1
def sanitize(object) #:nodoc:
-
connection.quote(object)
-
end
-
-
1
protected
-
-
# Accepts an array, hash, or string of SQL conditions and sanitizes
-
# them into a valid SQL fragment for a WHERE clause.
-
# ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
-
# { :name => "foo'bar", :group_id => 4 } returns "name='foo''bar' and group_id='4'"
-
# "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'"
-
1
def sanitize_sql_for_conditions(condition, table_name = self.table_name)
-
return nil if condition.blank?
-
-
case condition
-
when Array; sanitize_sql_array(condition)
-
when Hash; sanitize_sql_hash_for_conditions(condition, table_name)
-
else condition
-
end
-
end
-
1
alias_method :sanitize_sql, :sanitize_sql_for_conditions
-
-
# Accepts an array, hash, or string of SQL conditions and sanitizes
-
# them into a valid SQL fragment for a SET clause.
-
# { :name => nil, :group_id => 4 } returns "name = NULL , group_id='4'"
-
1
def sanitize_sql_for_assignment(assignments)
-
case assignments
-
when Array; sanitize_sql_array(assignments)
-
when Hash; sanitize_sql_hash_for_assignment(assignments)
-
else assignments
-
end
-
end
-
-
# Accepts a hash of SQL conditions and replaces those attributes
-
# that correspond to a +composed_of+ relationship with their expanded
-
# aggregate attribute values.
-
# Given:
-
# class Person < ActiveRecord::Base
-
# composed_of :address, :class_name => "Address",
-
# :mapping => [%w(address_street street), %w(address_city city)]
-
# end
-
# Then:
-
# { :address => Address.new("813 abc st.", "chicago") }
-
# # => { :address_street => "813 abc st.", :address_city => "chicago" }
-
1
def expand_hash_conditions_for_aggregates(attrs)
-
expanded_attrs = {}
-
attrs.each do |attr, value|
-
if aggregation = reflect_on_aggregation(attr.to_sym)
-
mapping = aggregation.mapping
-
mapping.each do |field_attr, aggregate_attr|
-
if mapping.size == 1 && !value.respond_to?(aggregate_attr)
-
expanded_attrs[field_attr] = value
-
else
-
expanded_attrs[field_attr] = value.send(aggregate_attr)
-
end
-
end
-
else
-
expanded_attrs[attr] = value
-
end
-
end
-
expanded_attrs
-
end
-
-
# Sanitizes a hash of attribute/value pairs into SQL conditions for a WHERE clause.
-
# { :name => "foo'bar", :group_id => 4 }
-
# # => "name='foo''bar' and group_id= 4"
-
# { :status => nil, :group_id => [1,2,3] }
-
# # => "status IS NULL and group_id IN (1,2,3)"
-
# { :age => 13..18 }
-
# # => "age BETWEEN 13 AND 18"
-
# { 'other_records.id' => 7 }
-
# # => "`other_records`.`id` = 7"
-
# { :other_records => { :id => 7 } }
-
# # => "`other_records`.`id` = 7"
-
# And for value objects on a composed_of relationship:
-
# { :address => Address.new("123 abc st.", "chicago") }
-
# # => "address_street='123 abc st.' and address_city='chicago'"
-
1
def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name)
-
attrs = expand_hash_conditions_for_aggregates(attrs)
-
-
table = Arel::Table.new(table_name, arel_engine).alias(default_table_name)
-
PredicateBuilder.build_from_hash(self.class, attrs, table).map { |b|
-
connection.visitor.accept b
-
}.join(' AND ')
-
end
-
1
alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions
-
-
# Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause.
-
# { :status => nil, :group_id => 1 }
-
# # => "status = NULL , group_id = 1"
-
1
def sanitize_sql_hash_for_assignment(attrs)
-
attrs.map do |attr, value|
-
"#{connection.quote_column_name(attr)} = #{quote_bound_value(value)}"
-
end.join(', ')
-
end
-
-
# Accepts an array of conditions. The array has each value
-
# sanitized and interpolated into the SQL statement.
-
# ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
-
1
def sanitize_sql_array(ary)
-
statement, *values = ary
-
if values.first.is_a?(Hash) && statement =~ /:\w+/
-
replace_named_bind_variables(statement, values.first)
-
elsif statement.include?('?')
-
replace_bind_variables(statement, values)
-
elsif statement.blank?
-
statement
-
else
-
statement % values.collect { |value| connection.quote_string(value.to_s) }
-
end
-
end
-
-
1
alias_method :sanitize_conditions, :sanitize_sql
-
-
1
def replace_bind_variables(statement, values) #:nodoc:
-
raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size)
-
bound = values.dup
-
c = connection
-
statement.gsub('?') { quote_bound_value(bound.shift, c) }
-
end
-
-
1
def replace_named_bind_variables(statement, bind_vars) #:nodoc:
-
statement.gsub(/(:?):([a-zA-Z]\w*)/) do
-
if $1 == ':' # skip postgresql casts
-
$& # return the whole match
-
elsif bind_vars.include?(match = $2.to_sym)
-
quote_bound_value(bind_vars[match])
-
else
-
raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}"
-
end
-
end
-
end
-
-
1
def quote_bound_value(value, c = connection) #:nodoc:
-
if value.respond_to?(:map) && !value.acts_like?(:string)
-
if value.respond_to?(:empty?) && value.empty?
-
c.quote(nil)
-
else
-
value.map { |v| c.quote(v) }.join(',')
-
end
-
else
-
c.quote(value)
-
end
-
end
-
-
1
def raise_if_bind_arity_mismatch(statement, expected, provided) #:nodoc:
-
unless expected == provided
-
raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}"
-
end
-
end
-
end
-
-
# TODO: Deprecate this
-
1
def quoted_id
-
self.class.quote_value(id, column_for_attribute(self.class.primary_key))
-
end
-
end
-
end
-
-
1
module ActiveRecord
-
1
module Scoping
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
include Default
-
1
include Named
-
end
-
-
1
module ClassMethods
-
1
def current_scope #:nodoc:
-
Thread.current["#{self}_current_scope"]
-
end
-
-
1
def current_scope=(scope) #:nodoc:
-
Thread.current["#{self}_current_scope"] = scope
-
end
-
end
-
-
1
def populate_with_current_scope_attributes
-
return unless self.class.scope_attributes?
-
-
self.class.scope_attributes.each do |att,value|
-
send("#{att}=", value) if respond_to?("#{att}=")
-
end
-
end
-
-
end
-
end
-
1
require 'active_support/core_ext/array'
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
-
1
module ActiveRecord
-
# = Active Record \Named \Scopes
-
1
module Scoping
-
1
module Named
-
1
extend ActiveSupport::Concern
-
-
1
module ClassMethods
-
# Returns an <tt>ActiveRecord::Relation</tt> scope object.
-
#
-
# posts = Post.all
-
# posts.size # Fires "select count(*) from posts" and returns the count
-
# posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
-
#
-
# fruits = Fruit.all
-
# fruits = fruits.where(color: 'red') if options[:red_only]
-
# fruits = fruits.limit(10) if limited?
-
#
-
# You can define a scope that applies to all finders using
-
# <tt>ActiveRecord::Base.default_scope</tt>.
-
1
def all
-
if current_scope
-
current_scope.clone
-
else
-
scope = relation
-
scope.default_scoped = true
-
scope
-
end
-
end
-
-
# Collects attributes from scopes that should be applied when creating
-
# an AR instance for the particular class this is called on.
-
1
def scope_attributes # :nodoc:
-
if current_scope
-
current_scope.scope_for_create
-
else
-
scope = relation
-
scope.default_scoped = true
-
scope.scope_for_create
-
end
-
end
-
-
# Are there default attributes associated with this scope?
-
1
def scope_attributes? # :nodoc:
-
current_scope || default_scopes.any?
-
end
-
-
# Adds a class method for retrieving and querying objects. A \scope
-
# represents a narrowing of a database query, such as
-
# <tt>where(color: :red).select('shirts.*').includes(:washing_instructions)</tt>.
-
#
-
# class Shirt < ActiveRecord::Base
-
# scope :red, -> { where(color: 'red') }
-
# scope :dry_clean_only, -> { joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true) }
-
# end
-
#
-
# The above calls to +scope+ define class methods <tt>Shirt.red</tt> and
-
# <tt>Shirt.dry_clean_only</tt>. <tt>Shirt.red</tt>, in effect,
-
# represents the query <tt>Shirt.where(color: 'red')</tt>.
-
#
-
# You should always pass a callable object to the scopes defined
-
# with +scope+. This ensures that the scope is re-evaluated each
-
# time it is called.
-
#
-
# Note that this is simply 'syntactic sugar' for defining an actual
-
# class method:
-
#
-
# class Shirt < ActiveRecord::Base
-
# def self.red
-
# where(color: 'red')
-
# end
-
# end
-
#
-
# Unlike <tt>Shirt.find(...)</tt>, however, the object returned by
-
# <tt>Shirt.red</tt> is not an Array; it resembles the association object
-
# constructed by a +has_many+ declaration. For instance, you can invoke
-
# <tt>Shirt.red.first</tt>, <tt>Shirt.red.count</tt>,
-
# <tt>Shirt.red.where(size: 'small')</tt>. Also, just as with the
-
# association objects, named \scopes act like an Array, implementing
-
# Enumerable; <tt>Shirt.red.each(&block)</tt>, <tt>Shirt.red.first</tt>,
-
# and <tt>Shirt.red.inject(memo, &block)</tt> all behave as if
-
# <tt>Shirt.red</tt> really was an Array.
-
#
-
# These named \scopes are composable. For instance,
-
# <tt>Shirt.red.dry_clean_only</tt> will produce all shirts that are
-
# both red and dry clean only. Nested finds and calculations also work
-
# with these compositions: <tt>Shirt.red.dry_clean_only.count</tt>
-
# returns the number of garments for which these criteria obtain.
-
# Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
-
#
-
# All scopes are available as class methods on the ActiveRecord::Base
-
# descendant upon which the \scopes were defined. But they are also
-
# available to +has_many+ associations. If,
-
#
-
# class Person < ActiveRecord::Base
-
# has_many :shirts
-
# end
-
#
-
# then <tt>elton.shirts.red.dry_clean_only</tt> will return all of
-
# Elton's red, dry clean only shirts.
-
#
-
# \Named scopes can also have extensions, just as with +has_many+
-
# declarations:
-
#
-
# class Shirt < ActiveRecord::Base
-
# scope :red, -> { where(color: 'red') } do
-
# def dom_id
-
# 'red_shirts'
-
# end
-
# end
-
# end
-
#
-
# Scopes can also be used while creating/building a record.
-
#
-
# class Article < ActiveRecord::Base
-
# scope :published, -> { where(published: true) }
-
# end
-
#
-
# Article.published.new.published # => true
-
# Article.published.create.published # => true
-
#
-
# \Class methods on your model are automatically available
-
# on scopes. Assuming the following setup:
-
#
-
# class Article < ActiveRecord::Base
-
# scope :published, -> { where(published: true) }
-
# scope :featured, -> { where(featured: true) }
-
#
-
# def self.latest_article
-
# order('published_at desc').first
-
# end
-
#
-
# def self.titles
-
# map(&:title)
-
# end
-
#
-
# end
-
#
-
# We are able to call the methods like this:
-
#
-
# Article.published.featured.latest_article
-
# Article.featured.titles
-
-
1
def scope(name, body, &block)
-
extension = Module.new(&block) if block
-
-
# Check body.is_a?(Relation) to prevent the relation actually being
-
# loaded by respond_to?
-
if body.is_a?(Relation) || !body.respond_to?(:call)
-
ActiveSupport::Deprecation.warn(
-
"Using #scope without passing a callable object is deprecated. For " \
-
"example `scope :red, where(color: 'red')` should be changed to " \
-
"`scope :red, -> { where(color: 'red') }`. There are numerous gotchas " \
-
"in the former usage and it makes the implementation more complicated " \
-
"and buggy. (If you prefer, you can just define a class method named " \
-
"`self.red`.)"
-
)
-
end
-
-
singleton_class.send(:define_method, name) do |*args|
-
options = body.respond_to?(:call) ? unscoped { body.call(*args) } : body
-
relation = all.merge(options)
-
-
extension ? relation.extending(extension) : relation
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveRecord #:nodoc:
-
# = Active Record Serialization
-
1
module Serialization
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::Serializers::JSON
-
-
1
included do
-
1
self.include_root_in_json = true
-
end
-
-
1
def serializable_hash(options = nil)
-
options = options.try(:clone) || {}
-
-
options[:except] = Array(options[:except]).map { |n| n.to_s }
-
options[:except] |= Array(self.class.inheritance_column)
-
-
super(options)
-
end
-
end
-
end
-
-
1
require 'active_record/serializers/xml_serializer'
-
1
require 'active_support/core_ext/hash/conversions'
-
-
1
module ActiveRecord #:nodoc:
-
1
module Serialization
-
1
include ActiveModel::Serializers::Xml
-
-
# Builds an XML document to represent the model. Some configuration is
-
# available through +options+. However more complicated cases should
-
# override ActiveRecord::Base#to_xml.
-
#
-
# By default the generated XML document will include the processing
-
# instruction and all the object's attributes. For example:
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <topic>
-
# <title>The First Topic</title>
-
# <author-name>David</author-name>
-
# <id type="integer">1</id>
-
# <approved type="boolean">false</approved>
-
# <replies-count type="integer">0</replies-count>
-
# <bonus-time type="dateTime">2000-01-01T08:28:00+12:00</bonus-time>
-
# <written-on type="dateTime">2003-07-16T09:28:00+1200</written-on>
-
# <content>Have a nice day</content>
-
# <author-email-address>david@loudthinking.com</author-email-address>
-
# <parent-id></parent-id>
-
# <last-read type="date">2004-04-15</last-read>
-
# </topic>
-
#
-
# This behavior can be controlled with <tt>:only</tt>, <tt>:except</tt>,
-
# <tt>:skip_instruct</tt>, <tt>:skip_types</tt>, <tt>:dasherize</tt> and <tt>:camelize</tt> .
-
# The <tt>:only</tt> and <tt>:except</tt> options are the same as for the
-
# +attributes+ method. The default is to dasherize all column names, but you
-
# can disable this setting <tt>:dasherize</tt> to +false+. Setting <tt>:camelize</tt>
-
# to +true+ will camelize all column names - this also overrides <tt>:dasherize</tt>.
-
# To not have the column type included in the XML output set <tt>:skip_types</tt> to +true+.
-
#
-
# For instance:
-
#
-
# topic.to_xml(:skip_instruct => true, :except => [ :id, :bonus_time, :written_on, :replies_count ])
-
#
-
# <topic>
-
# <title>The First Topic</title>
-
# <author-name>David</author-name>
-
# <approved type="boolean">false</approved>
-
# <content>Have a nice day</content>
-
# <author-email-address>david@loudthinking.com</author-email-address>
-
# <parent-id></parent-id>
-
# <last-read type="date">2004-04-15</last-read>
-
# </topic>
-
#
-
# To include first level associations use <tt>:include</tt>:
-
#
-
# firm.to_xml :include => [ :account, :clients ]
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <firm>
-
# <id type="integer">1</id>
-
# <rating type="integer">1</rating>
-
# <name>37signals</name>
-
# <clients type="array">
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Summit</name>
-
# </client>
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Microsoft</name>
-
# </client>
-
# </clients>
-
# <account>
-
# <id type="integer">1</id>
-
# <credit-limit type="integer">50</credit-limit>
-
# </account>
-
# </firm>
-
#
-
# Additionally, the record being serialized will be passed to a Proc's second
-
# parameter. This allows for ad hoc additions to the resultant document that
-
# incorporate the context of the record being serialized. And by leveraging the
-
# closure created by a Proc, to_xml can be used to add elements that normally fall
-
# outside of the scope of the model -- for example, generating and appending URLs
-
# associated with models.
-
#
-
# proc = Proc.new { |options, record| options[:builder].tag!('name-reverse', record.name.reverse) }
-
# firm.to_xml :procs => [ proc ]
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <name-reverse>slangis73</name-reverse>
-
# </firm>
-
#
-
# To include deeper levels of associations pass a hash like this:
-
#
-
# firm.to_xml :include => {:account => {}, :clients => {:include => :address}}
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <firm>
-
# <id type="integer">1</id>
-
# <rating type="integer">1</rating>
-
# <name>37signals</name>
-
# <clients type="array">
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Summit</name>
-
# <address>
-
# ...
-
# </address>
-
# </client>
-
# <client>
-
# <rating type="integer">1</rating>
-
# <name>Microsoft</name>
-
# <address>
-
# ...
-
# </address>
-
# </client>
-
# </clients>
-
# <account>
-
# <id type="integer">1</id>
-
# <credit-limit type="integer">50</credit-limit>
-
# </account>
-
# </firm>
-
#
-
# To include any methods on the model being called use <tt>:methods</tt>:
-
#
-
# firm.to_xml :methods => [ :calculated_earnings, :real_earnings ]
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <calculated-earnings>100000000000000000</calculated-earnings>
-
# <real-earnings>5</real-earnings>
-
# </firm>
-
#
-
# To call any additional Procs use <tt>:procs</tt>. The Procs are passed a
-
# modified version of the options hash that was given to +to_xml+:
-
#
-
# proc = Proc.new { |options| options[:builder].tag!('abc', 'def') }
-
# firm.to_xml :procs => [ proc ]
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <abc>def</abc>
-
# </firm>
-
#
-
# Alternatively, you can yield the builder object as part of the +to_xml+ call:
-
#
-
# firm.to_xml do |xml|
-
# xml.creator do
-
# xml.first_name "David"
-
# xml.last_name "Heinemeier Hansson"
-
# end
-
# end
-
#
-
# <firm>
-
# # ... normal attributes as shown above ...
-
# <creator>
-
# <first_name>David</first_name>
-
# <last_name>Heinemeier Hansson</last_name>
-
# </creator>
-
# </firm>
-
#
-
# As noted above, you may override +to_xml+ in your ActiveRecord::Base
-
# subclasses to have complete control about what's generated. The general
-
# form of doing this is:
-
#
-
# class IHaveMyOwnXML < ActiveRecord::Base
-
# def to_xml(options = {})
-
# require 'builder'
-
# options[:indent] ||= 2
-
# xml = options[:builder] ||= ::Builder::XmlMarkup.new(:indent => options[:indent])
-
# xml.instruct! unless options[:skip_instruct]
-
# xml.level_one do
-
# xml.tag!(:second_level, 'content')
-
# end
-
# end
-
# end
-
1
def to_xml(options = {}, &block)
-
XmlSerializer.new(self, options).serialize(&block)
-
end
-
end
-
-
1
class XmlSerializer < ActiveModel::Serializers::Xml::Serializer #:nodoc:
-
1
class Attribute < ActiveModel::Serializers::Xml::Serializer::Attribute #:nodoc:
-
1
def compute_type
-
klass = @serializable.class
-
type = if klass.serialized_attributes.key?(name)
-
super
-
elsif klass.columns_hash.key?(name)
-
klass.columns_hash[name].type
-
else
-
NilClass
-
end
-
-
{ :text => :string,
-
:time => :datetime }[type] || type
-
end
-
1
protected :compute_type
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
-
1
module ActiveRecord
-
# Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column.
-
# It's like a simple key/value store baked into your record when you don't care about being able to
-
# query that store outside the context of a single record.
-
#
-
# You can then declare accessors to this store that are then accessible just like any other attribute
-
# of the model. This is very helpful for easily exposing store keys to a form or elsewhere that's
-
# already built around just accessing attributes on the model.
-
#
-
# Make sure that you declare the database column used for the serialized store as a text, so there's
-
# plenty of room.
-
#
-
# You can set custom coder to encode/decode your serialized attributes to/from different formats.
-
# JSON, YAML, Marshal are supported out of the box. Generally it can be any wrapper that provides +load+ and +dump+.
-
#
-
# Examples:
-
#
-
# class User < ActiveRecord::Base
-
# store :settings, accessors: [ :color, :homepage ], coder: JSON
-
# end
-
#
-
# u = User.new(color: 'black', homepage: '37signals.com')
-
# u.color # Accessor stored attribute
-
# u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor
-
#
-
# # There is no difference between strings and symbols for accessing custom attributes
-
# u.settings[:country] # => 'Denmark'
-
# u.settings['country'] # => 'Denmark'
-
#
-
# # Add additional accessors to an existing store through store_accessor
-
# class SuperUser < User
-
# store_accessor :settings, :privileges, :servants
-
# end
-
#
-
# The stored attribute names can be retrieved using +stored_attributes+.
-
#
-
# User.stored_attributes[:settings] # [:color, :homepage]
-
#
-
# == Overwriting default accessors
-
#
-
# All stored values are automatically available through accessors on the Active Record
-
# object, but sometimes you want to specialize this behavior. This can be done by overwriting
-
# the default accessors (using the same name as the attribute) and calling
-
# <tt>read_store_attribute(store_attribute_name, attr_name)</tt> and
-
# <tt>write_store_attribute(store_attribute_name, attr_name, value)</tt> to actually
-
# change things.
-
#
-
# class Song < ActiveRecord::Base
-
# # Uses a stored integer to hold the volume adjustment of the song
-
# store :settings, accessors: [:volume_adjustment]
-
#
-
# def volume_adjustment=(decibels)
-
# write_store_attribute(:settings, :volume_adjustment, decibels.to_i)
-
# end
-
#
-
# def volume_adjustment
-
# read_store_attribute(:settings, :volume_adjustment).to_i
-
# end
-
# end
-
1
module Store
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
class_attribute :stored_attributes, instance_accessor: false
-
1
self.stored_attributes = {}
-
end
-
-
1
module ClassMethods
-
1
def store(store_attribute, options = {})
-
serialize store_attribute, IndifferentCoder.new(options[:coder])
-
store_accessor(store_attribute, options[:accessors]) if options.has_key? :accessors
-
end
-
-
1
def store_accessor(store_attribute, *keys)
-
keys = keys.flatten
-
keys.each do |key|
-
define_method("#{key}=") do |value|
-
write_store_attribute(store_attribute, key, value)
-
end
-
-
define_method(key) do
-
read_store_attribute(store_attribute, key)
-
end
-
end
-
-
self.stored_attributes[store_attribute] ||= []
-
self.stored_attributes[store_attribute] |= keys
-
end
-
end
-
-
1
protected
-
1
def read_store_attribute(store_attribute, key)
-
attribute = initialize_store_attribute(store_attribute)
-
attribute[key]
-
end
-
-
1
def write_store_attribute(store_attribute, key, value)
-
attribute = initialize_store_attribute(store_attribute)
-
if value != attribute[key]
-
send :"#{store_attribute}_will_change!"
-
attribute[key] = value
-
end
-
end
-
-
1
private
-
1
def initialize_store_attribute(store_attribute)
-
attribute = send(store_attribute)
-
unless attribute.is_a?(HashWithIndifferentAccess)
-
attribute = IndifferentCoder.as_indifferent_hash(attribute)
-
send :"#{store_attribute}=", attribute
-
end
-
attribute
-
end
-
-
1
class IndifferentCoder # :nodoc:
-
1
def initialize(coder_or_class_name)
-
@coder =
-
if coder_or_class_name.respond_to?(:load) && coder_or_class_name.respond_to?(:dump)
-
coder_or_class_name
-
else
-
ActiveRecord::Coders::YAMLColumn.new(coder_or_class_name || Object)
-
end
-
end
-
-
1
def dump(obj)
-
@coder.dump self.class.as_indifferent_hash(obj)
-
end
-
-
1
def load(yaml)
-
self.class.as_indifferent_hash @coder.load(yaml)
-
end
-
-
1
def self.as_indifferent_hash(obj)
-
case obj
-
when HashWithIndifferentAccess
-
obj
-
when Hash
-
obj.with_indifferent_access
-
else
-
HashWithIndifferentAccess.new
-
end
-
end
-
end
-
end
-
end
-
1
require 'thread'
-
-
1
module ActiveRecord
-
# See ActiveRecord::Transactions::ClassMethods for documentation.
-
1
module Transactions
-
1
extend ActiveSupport::Concern
-
-
1
class TransactionError < ActiveRecordError # :nodoc:
-
end
-
-
1
included do
-
1
define_callbacks :commit, :rollback, :terminator => "result == false", :scope => [:kind, :name]
-
end
-
-
# = Active Record Transactions
-
#
-
# Transactions are protective blocks where SQL statements are only permanent
-
# if they can all succeed as one atomic action. The classic example is a
-
# transfer between two accounts where you can only have a deposit if the
-
# withdrawal succeeded and vice versa. Transactions enforce the integrity of
-
# the database and guard the data against program errors or database
-
# break-downs. So basically you should use transaction blocks whenever you
-
# have a number of statements that must be executed together or not at all.
-
#
-
# For example:
-
#
-
# ActiveRecord::Base.transaction do
-
# david.withdrawal(100)
-
# mary.deposit(100)
-
# end
-
#
-
# This example will only take money from David and give it to Mary if neither
-
# +withdrawal+ nor +deposit+ raise an exception. Exceptions will force a
-
# ROLLBACK that returns the database to the state before the transaction
-
# began. Be aware, though, that the objects will _not_ have their instance
-
# data returned to their pre-transactional state.
-
#
-
# == Different Active Record classes in a single transaction
-
#
-
# Though the transaction class method is called on some Active Record class,
-
# the objects within the transaction block need not all be instances of
-
# that class. This is because transactions are per-database connection, not
-
# per-model.
-
#
-
# In this example a +balance+ record is transactionally saved even
-
# though +transaction+ is called on the +Account+ class:
-
#
-
# Account.transaction do
-
# balance.save!
-
# account.save!
-
# end
-
#
-
# The +transaction+ method is also available as a model instance method.
-
# For example, you can also do this:
-
#
-
# balance.transaction do
-
# balance.save!
-
# account.save!
-
# end
-
#
-
# == Transactions are not distributed across database connections
-
#
-
# A transaction acts on a single database connection. If you have
-
# multiple class-specific databases, the transaction will not protect
-
# interaction among them. One workaround is to begin a transaction
-
# on each class whose models you alter:
-
#
-
# Student.transaction do
-
# Course.transaction do
-
# course.enroll(student)
-
# student.units += course.units
-
# end
-
# end
-
#
-
# This is a poor solution, but fully distributed transactions are beyond
-
# the scope of Active Record.
-
#
-
# == +save+ and +destroy+ are automatically wrapped in a transaction
-
#
-
# Both +save+ and +destroy+ come wrapped in a transaction that ensures
-
# that whatever you do in validations or callbacks will happen under its
-
# protected cover. So you can use validations to check for values that
-
# the transaction depends on or you can raise exceptions in the callbacks
-
# to rollback, including <tt>after_*</tt> callbacks.
-
#
-
# As a consequence changes to the database are not seen outside your connection
-
# until the operation is complete. For example, if you try to update the index
-
# of a search engine in +after_save+ the indexer won't see the updated record.
-
# The +after_commit+ callback is the only one that is triggered once the update
-
# is committed. See below.
-
#
-
# == Exception handling and rolling back
-
#
-
# Also have in mind that exceptions thrown within a transaction block will
-
# be propagated (after triggering the ROLLBACK), so you should be ready to
-
# catch those in your application code.
-
#
-
# One exception is the <tt>ActiveRecord::Rollback</tt> exception, which will trigger
-
# a ROLLBACK when raised, but not be re-raised by the transaction block.
-
#
-
# *Warning*: one should not catch <tt>ActiveRecord::StatementInvalid</tt> exceptions
-
# inside a transaction block. <tt>ActiveRecord::StatementInvalid</tt> exceptions indicate that an
-
# error occurred at the database level, for example when a unique constraint
-
# is violated. On some database systems, such as PostgreSQL, database errors
-
# inside a transaction cause the entire transaction to become unusable
-
# until it's restarted from the beginning. Here is an example which
-
# demonstrates the problem:
-
#
-
# # Suppose that we have a Number model with a unique column called 'i'.
-
# Number.transaction do
-
# Number.create(:i => 0)
-
# begin
-
# # This will raise a unique constraint error...
-
# Number.create(:i => 0)
-
# rescue ActiveRecord::StatementInvalid
-
# # ...which we ignore.
-
# end
-
#
-
# # On PostgreSQL, the transaction is now unusable. The following
-
# # statement will cause a PostgreSQL error, even though the unique
-
# # constraint is no longer violated:
-
# Number.create(:i => 1)
-
# # => "PGError: ERROR: current transaction is aborted, commands
-
# # ignored until end of transaction block"
-
# end
-
#
-
# One should restart the entire transaction if an
-
# <tt>ActiveRecord::StatementInvalid</tt> occurred.
-
#
-
# == Nested transactions
-
#
-
# +transaction+ calls can be nested. By default, this makes all database
-
# statements in the nested transaction block become part of the parent
-
# transaction. For example, the following behavior may be surprising:
-
#
-
# User.transaction do
-
# User.create(:username => 'Kotori')
-
# User.transaction do
-
# User.create(:username => 'Nemu')
-
# raise ActiveRecord::Rollback
-
# end
-
# end
-
#
-
# creates both "Kotori" and "Nemu". Reason is the <tt>ActiveRecord::Rollback</tt>
-
# exception in the nested block does not issue a ROLLBACK. Since these exceptions
-
# are captured in transaction blocks, the parent block does not see it and the
-
# real transaction is committed.
-
#
-
# In order to get a ROLLBACK for the nested transaction you may ask for a real
-
# sub-transaction by passing <tt>:requires_new => true</tt>. If anything goes wrong,
-
# the database rolls back to the beginning of the sub-transaction without rolling
-
# back the parent transaction. If we add it to the previous example:
-
#
-
# User.transaction do
-
# User.create(:username => 'Kotori')
-
# User.transaction(:requires_new => true) do
-
# User.create(:username => 'Nemu')
-
# raise ActiveRecord::Rollback
-
# end
-
# end
-
#
-
# only "Kotori" is created. (This works on MySQL and PostgreSQL, but not on SQLite3.)
-
#
-
# Most databases don't support true nested transactions. At the time of
-
# writing, the only database that we're aware of that supports true nested
-
# transactions, is MS-SQL. Because of this, Active Record emulates nested
-
# transactions by using savepoints on MySQL and PostgreSQL. See
-
# http://dev.mysql.com/doc/refman/5.6/en/savepoint.html
-
# for more information about savepoints.
-
#
-
# === Callbacks
-
#
-
# There are two types of callbacks associated with committing and rolling back transactions:
-
# +after_commit+ and +after_rollback+.
-
#
-
# +after_commit+ callbacks are called on every record saved or destroyed within a
-
# transaction immediately after the transaction is committed. +after_rollback+ callbacks
-
# are called on every record saved or destroyed within a transaction immediately after the
-
# transaction or savepoint is rolled back.
-
#
-
# These callbacks are useful for interacting with other systems since you will be guaranteed
-
# that the callback is only executed when the database is in a permanent state. For example,
-
# +after_commit+ is a good spot to put in a hook to clearing a cache since clearing it from
-
# within a transaction could trigger the cache to be regenerated before the database is updated.
-
#
-
# === Caveats
-
#
-
# If you're on MySQL, then do not use DDL operations in nested transactions
-
# blocks that are emulated with savepoints. That is, do not execute statements
-
# like 'CREATE TABLE' inside such blocks. This is because MySQL automatically
-
# releases all savepoints upon executing a DDL operation. When +transaction+
-
# is finished and tries to release the savepoint it created earlier, a
-
# database error will occur because the savepoint has already been
-
# automatically released. The following example demonstrates the problem:
-
#
-
# Model.connection.transaction do # BEGIN
-
# Model.connection.transaction(:requires_new => true) do # CREATE SAVEPOINT active_record_1
-
# Model.connection.create_table(...) # active_record_1 now automatically released
-
# end # RELEASE savepoint active_record_1
-
# # ^^^^ BOOM! database error!
-
# end
-
#
-
# Note that "TRUNCATE" is also a MySQL DDL statement!
-
1
module ClassMethods
-
# See ActiveRecord::Transactions::ClassMethods for detailed documentation.
-
1
def transaction(options = {}, &block)
-
# See the ConnectionAdapters::DatabaseStatements#transaction API docs.
-
connection.transaction(options, &block)
-
end
-
-
# This callback is called after a record has been created, updated, or destroyed.
-
#
-
# You can specify that the callback should only be fired by a certain action with
-
# the +:on+ option:
-
#
-
# after_commit :do_foo, :on => :create
-
# after_commit :do_bar, :on => :update
-
# after_commit :do_baz, :on => :destroy
-
#
-
# Also, to have the callback fired on create and update, but not on destroy:
-
#
-
# after_commit :do_zoo, :if => :persisted?
-
#
-
# Note that transactional fixtures do not play well with this feature. Please
-
# use the +test_after_commit+ gem to have these hooks fired in tests.
-
1
def after_commit(*args, &block)
-
options = args.last
-
if options.is_a?(Hash) && options[:on]
-
options[:if] = Array(options[:if])
-
options[:if] << "transaction_include_action?(:#{options[:on]})"
-
end
-
set_callback(:commit, :after, *args, &block)
-
end
-
-
# This callback is called after a create, update, or destroy are rolled back.
-
#
-
# Please check the documentation of +after_commit+ for options.
-
1
def after_rollback(*args, &block)
-
options = args.last
-
if options.is_a?(Hash) && options[:on]
-
options[:if] = Array(options[:if])
-
options[:if] << "transaction_include_action?(:#{options[:on]})"
-
end
-
set_callback(:rollback, :after, *args, &block)
-
end
-
end
-
-
# See ActiveRecord::Transactions::ClassMethods for detailed documentation.
-
1
def transaction(options = {}, &block)
-
self.class.transaction(options, &block)
-
end
-
-
1
def destroy #:nodoc:
-
with_transaction_returning_status { super }
-
end
-
-
1
def save(*) #:nodoc:
-
rollback_active_record_state! do
-
with_transaction_returning_status { super }
-
end
-
end
-
-
1
def save!(*) #:nodoc:
-
with_transaction_returning_status { super }
-
end
-
-
# Reset id and @new_record if the transaction rolls back.
-
1
def rollback_active_record_state!
-
remember_transaction_record_state
-
yield
-
rescue Exception
-
restore_transaction_record_state
-
raise
-
ensure
-
clear_transaction_record_state
-
end
-
-
# Call the after_commit callbacks
-
1
def committed! #:nodoc:
-
run_callbacks :commit
-
ensure
-
clear_transaction_record_state
-
end
-
-
# Call the after rollback callbacks. The restore_state argument indicates if the record
-
# state should be rolled back to the beginning or just to the last savepoint.
-
1
def rolledback!(force_restore_state = false) #:nodoc:
-
run_callbacks :rollback
-
ensure
-
restore_transaction_record_state(force_restore_state)
-
end
-
-
# Add the record to the current transaction so that the :after_rollback and :after_commit callbacks
-
# can be called.
-
1
def add_to_transaction
-
if self.class.connection.add_transaction_record(self)
-
remember_transaction_record_state
-
end
-
end
-
-
# Executes +method+ within a transaction and captures its return value as a
-
# status flag. If the status is true the transaction is committed, otherwise
-
# a ROLLBACK is issued. In any case the status flag is returned.
-
#
-
# This method is available within the context of an ActiveRecord::Base
-
# instance.
-
1
def with_transaction_returning_status
-
status = nil
-
self.class.transaction do
-
add_to_transaction
-
begin
-
status = yield
-
rescue ActiveRecord::Rollback
-
@_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
-
status = nil
-
end
-
-
raise ActiveRecord::Rollback unless status
-
end
-
status
-
end
-
-
1
protected
-
-
# Save the new record state and id of a record so it can be restored later if a transaction fails.
-
1
def remember_transaction_record_state #:nodoc:
-
@_start_transaction_state[:id] = id if has_attribute?(self.class.primary_key)
-
@_start_transaction_state[:new_record] = @new_record
-
@_start_transaction_state[:destroyed] = @destroyed
-
@_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) + 1
-
@_start_transaction_state[:frozen?] = @attributes.frozen?
-
end
-
-
# Clear the new record state and id of a record.
-
1
def clear_transaction_record_state #:nodoc:
-
@_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
-
@_start_transaction_state.clear if @_start_transaction_state[:level] < 1
-
end
-
-
# Restore the new record state and id of a record that was previously saved by a call to save_record_state.
-
1
def restore_transaction_record_state(force = false) #:nodoc:
-
unless @_start_transaction_state.empty?
-
@_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
-
if @_start_transaction_state[:level] < 1 || force
-
restore_state = @_start_transaction_state
-
was_frozen = restore_state[:frozen?]
-
@attributes = @attributes.dup if @attributes.frozen?
-
@new_record = restore_state[:new_record]
-
@destroyed = restore_state[:destroyed]
-
if restore_state.has_key?(:id)
-
self.id = restore_state[:id]
-
else
-
@attributes.delete(self.class.primary_key)
-
@attributes_cache.delete(self.class.primary_key)
-
end
-
@attributes.freeze if was_frozen
-
@_start_transaction_state.clear
-
end
-
end
-
end
-
-
# Determine if a record was created or destroyed in a transaction. State should be one of :new_record or :destroyed.
-
1
def transaction_record_state(state) #:nodoc:
-
@_start_transaction_state[state]
-
end
-
-
# Determine if a transaction included an action for :create, :update, or :destroy. Used in filtering callbacks.
-
1
def transaction_include_action?(action) #:nodoc:
-
case action
-
when :create
-
transaction_record_state(:new_record)
-
when :destroy
-
destroyed?
-
when :update
-
!(transaction_record_state(:new_record) || destroyed?)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Translation
-
1
include ActiveModel::Translation
-
-
# Set the lookup ancestors for ActiveModel.
-
1
def lookup_ancestors #:nodoc:
-
klass = self
-
classes = [klass]
-
return classes if klass == ActiveRecord::Base
-
-
while klass != klass.base_class
-
classes << klass = klass.superclass
-
end
-
classes
-
end
-
-
# Set the i18n scope to overwrite ActiveModel.
-
1
def i18n_scope #:nodoc:
-
:activerecord
-
end
-
end
-
end
-
1
module ActiveRecord
-
# = Active Record RecordInvalid
-
#
-
# Raised by <tt>save!</tt> and <tt>create!</tt> when the record is invalid. Use the
-
# +record+ method to retrieve the record which did not validate.
-
#
-
# begin
-
# complex_operation_that_calls_save!_internally
-
# rescue ActiveRecord::RecordInvalid => invalid
-
# puts invalid.record.errors
-
# end
-
1
class RecordInvalid < ActiveRecordError
-
1
attr_reader :record # :nodoc:
-
1
def initialize(record) # :nodoc:
-
@record = record
-
errors = @record.errors.full_messages.join(", ")
-
super(I18n.t(:"#{@record.class.i18n_scope}.errors.messages.record_invalid", :errors => errors, :default => :"errors.messages.record_invalid"))
-
end
-
end
-
-
# = Active Record Validations
-
#
-
# Active Record includes the majority of its validations from <tt>ActiveModel::Validations</tt>
-
# all of which accept the <tt>:on</tt> argument to define the context where the
-
# validations are active. Active Record will always supply either the context of
-
# <tt>:create</tt> or <tt>:update</tt> dependent on whether the model is a
-
# <tt>new_record?</tt>.
-
1
module Validations
-
1
extend ActiveSupport::Concern
-
1
include ActiveModel::Validations
-
-
1
module ClassMethods
-
# Creates an object just like Base.create but calls <tt>save!</tt> instead of +save+
-
# so an exception is raised if the record is invalid.
-
1
def create!(attributes = nil, &block)
-
if attributes.is_a?(Array)
-
attributes.collect { |attr| create!(attr, &block) }
-
else
-
object = new(attributes)
-
yield(object) if block_given?
-
object.save!
-
object
-
end
-
end
-
end
-
-
# The validation process on save can be skipped by passing <tt>validate: false</tt>.
-
# The regular Base#save method is replaced with this when the validations
-
# module is mixed in, which it is by default.
-
1
def save(options={})
-
perform_validations(options) ? super : false
-
end
-
-
# Attempts to save the record just like Base#save but will raise a +RecordInvalid+
-
# exception instead of returning +false+ if the record is not valid.
-
1
def save!(options={})
-
perform_validations(options) ? super : raise(RecordInvalid.new(self))
-
end
-
-
# Runs all the validations within the specified context. Returns +true+ if
-
# no errors are found, +false+ otherwise.
-
#
-
# If the argument is +false+ (default is +nil+), the context is set to <tt>:create</tt> if
-
# <tt>new_record?</tt> is +true+, and to <tt>:update</tt> if it is not.
-
#
-
# Validations with no <tt>:on</tt> option will run no matter the context. Validations with
-
# some <tt>:on</tt> option will only run in the specified context.
-
1
def valid?(context = nil)
-
context ||= (new_record? ? :create : :update)
-
output = super(context)
-
errors.empty? && output
-
end
-
-
1
protected
-
-
1
def perform_validations(options={}) # :nodoc:
-
perform_validation = options[:validate] != false
-
perform_validation ? valid?(options[:context]) : true
-
end
-
end
-
end
-
-
1
require "active_record/validations/associated"
-
1
require "active_record/validations/uniqueness"
-
1
require "active_record/validations/presence"
-
1
module ActiveRecord
-
1
module Validations
-
1
class AssociatedValidator < ActiveModel::EachValidator #:nodoc:
-
1
def validate_each(record, attribute, value)
-
if Array.wrap(value).reject {|r| r.marked_for_destruction? || r.valid?(record.validation_context) }.any?
-
record.errors.add(attribute, :invalid, options.merge(:value => value))
-
end
-
end
-
end
-
-
1
module ClassMethods
-
# Validates whether the associated object or objects are all valid
-
# themselves. Works with any kind of association.
-
#
-
# class Book < ActiveRecord::Base
-
# has_many :pages
-
# belongs_to :library
-
#
-
# validates_associated :pages, :library
-
# end
-
#
-
# WARNING: This validation must not be used on both ends of an association.
-
# Doing so will lead to a circular dependency and cause infinite recursion.
-
#
-
# NOTE: This validation will not fail if the association hasn't been
-
# assigned. If you want to ensure that the association is both present and
-
# guaranteed to be valid, you also need to use +validates_presence_of+.
-
#
-
# Configuration options:
-
#
-
# * <tt>:message</tt> - A custom error message (default is: "is invalid").
-
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
-
# validation contexts by default (+nil+), other options are <tt>:create</tt>
-
# and <tt>:update</tt>.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or +false+
-
# value.
-
1
def validates_associated(*attr_names)
-
validates_with AssociatedValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module Validations
-
1
class PresenceValidator < ActiveModel::Validations::PresenceValidator # :nodoc:
-
1
def validate(record)
-
super
-
attributes.each do |attribute|
-
next unless record.class.reflect_on_association(attribute)
-
associated_records = Array(record.send(attribute))
-
-
# Superclass validates presence. Ensure present records aren't about to be destroyed.
-
if associated_records.present? && associated_records.all? { |r| r.marked_for_destruction? }
-
record.errors.add(attribute, :blank, options)
-
end
-
end
-
end
-
end
-
-
1
module ClassMethods
-
# Validates that the specified attributes are not blank (as defined by
-
# Object#blank?), and, if the attribute is an association, that the
-
# associated object is not marked for destruction. Happens by default
-
# on save.
-
#
-
# class Person < ActiveRecord::Base
-
# has_one :face
-
# validates_presence_of :face
-
# end
-
#
-
# The face attribute must be in the object and it cannot be blank or marked
-
# for destruction.
-
#
-
# If you want to validate the presence of a boolean field (where the real values
-
# are true and false), you will want to use
-
# <tt>validates_inclusion_of :field_name, in: [true, false]</tt>.
-
#
-
# This is due to the way Object#blank? handles boolean values:
-
# <tt>false.blank? # => true</tt>.
-
#
-
# This validator defers to the ActiveModel validation for presence, adding the
-
# check to see that an associated object is not marked for destruction. This
-
# prevents the parent object from validating successfully and saving, which then
-
# deletes the associated object, thus putting the parent object into an invalid
-
# state.
-
#
-
# Configuration options:
-
# * <tt>:message</tt> - A custom error message (default is: "can't be blank").
-
# * <tt>:on</tt> - Specifies when this validation is active. Runs in all
-
# validation contexts by default (+nil+), other options are <tt>:create</tt>
-
# and <tt>:update</tt>.
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if
-
# the validation should occur (e.g. <tt>if: :allow_validation</tt>, or
-
# <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc
-
# or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:strict</tt> - Specifies whether validation should be strict.
-
# See <tt>ActiveModel::Validation#validates!</tt> for more information.
-
1
def validates_presence_of(*attr_names)
-
validates_with PresenceValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/array/prepend_and_append'
-
-
1
module ActiveRecord
-
1
module Validations
-
1
class UniquenessValidator < ActiveModel::EachValidator # :nodoc:
-
1
def initialize(options)
-
super(options.reverse_merge(:case_sensitive => true))
-
end
-
-
# Unfortunately, we have to tie Uniqueness validators to a class.
-
1
def setup(klass)
-
@klass = klass
-
end
-
-
1
def validate_each(record, attribute, value)
-
finder_class = find_finder_class_for(record)
-
table = finder_class.arel_table
-
-
coder = record.class.serialized_attributes[attribute.to_s]
-
-
if value && coder
-
value = coder.dump value
-
end
-
-
relation = build_relation(finder_class, table, attribute, value)
-
relation = relation.and(table[finder_class.primary_key.to_sym].not_eq(record.send(:id))) if record.persisted?
-
-
Array(options[:scope]).each do |scope_item|
-
reflection = record.class.reflect_on_association(scope_item)
-
if reflection
-
scope_value = record.send(reflection.foreign_key)
-
scope_item = reflection.foreign_key
-
else
-
scope_value = record.read_attribute(scope_item)
-
end
-
relation = relation.and(table[scope_item].eq(scope_value))
-
end
-
-
relation = finder_class.unscoped.where(relation)
-
-
if options[:conditions]
-
relation = relation.merge(options[:conditions])
-
end
-
-
if relation.exists?
-
record.errors.add(attribute, :taken, options.except(:case_sensitive, :scope, :conditions).merge(:value => value))
-
end
-
end
-
-
1
protected
-
-
# The check for an existing value should be run from a class that
-
# isn't abstract. This means working down from the current class
-
# (self), to the first non-abstract class. Since classes don't know
-
# their subclasses, we have to build the hierarchy between self and
-
# the record's class.
-
1
def find_finder_class_for(record) #:nodoc:
-
class_hierarchy = [record.class]
-
-
while class_hierarchy.first != @klass
-
class_hierarchy.prepend(class_hierarchy.first.superclass)
-
end
-
-
class_hierarchy.detect { |klass| !klass.abstract_class? }
-
end
-
-
1
def build_relation(klass, table, attribute, value) #:nodoc:
-
if reflection = klass.reflect_on_association(attribute)
-
attribute = reflection.foreign_key
-
value = value.attributes[reflection.primary_key_column.name]
-
end
-
-
column = klass.columns_hash[attribute.to_s]
-
value = column.limit ? value.to_s[0, column.limit] : value.to_s if !value.nil? && column.text?
-
-
if !options[:case_sensitive] && value && column.text?
-
# will use SQL LOWER function before comparison, unless it detects a case insensitive collation
-
relation = klass.connection.case_insensitive_comparison(table, attribute, column, value)
-
else
-
value = klass.connection.case_sensitive_modifier(value) unless value.nil?
-
relation = table[attribute].eq(value)
-
end
-
-
relation
-
end
-
end
-
-
1
module ClassMethods
-
# Validates whether the value of the specified attributes are unique
-
# across the system. Useful for making sure that only one user
-
# can be named "davidhh".
-
#
-
# class Person < ActiveRecord::Base
-
# validates_uniqueness_of :user_name
-
# end
-
#
-
# It can also validate whether the value of the specified attributes are
-
# unique based on a <tt>:scope</tt> parameter:
-
#
-
# class Person < ActiveRecord::Base
-
# validates_uniqueness_of :user_name, scope: :account_id
-
# end
-
#
-
# Or even multiple scope parameters. For example, making sure that a
-
# teacher can only be on the schedule once per semester for a particular
-
# class.
-
#
-
# class TeacherSchedule < ActiveRecord::Base
-
# validates_uniqueness_of :teacher_id, scope: [:semester_id, :class_id]
-
# end
-
#
-
# It is also possible to limit the uniqueness constraint to a set of
-
# records matching certain conditions. In this example archived articles
-
# are not being taken into consideration when validating uniqueness
-
# of the title attribute:
-
#
-
# class Article < ActiveRecord::Base
-
# validates_uniqueness_of :title, conditions: where('status != ?', 'archived')
-
# end
-
#
-
# When the record is created, a check is performed to make sure that no
-
# record exists in the database with the given value for the specified
-
# attribute (that maps to a column). When the record is updated,
-
# the same check is made but disregarding the record itself.
-
#
-
# Configuration options:
-
#
-
# * <tt>:message</tt> - Specifies a custom error message (default is:
-
# "has already been taken").
-
# * <tt>:scope</tt> - One or more columns by which to limit the scope of
-
# the uniqueness constraint.
-
# * <tt>:conditions</tt> - Specify the conditions to be included as a
-
# <tt>WHERE</tt> SQL fragment to limit the uniqueness constraint lookup
-
# (e.g. <tt>conditions: where('status = ?', 'active')</tt>).
-
# * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by
-
# non-text columns (+true+ by default).
-
# * <tt>:allow_nil</tt> - If set to +true+, skips this validation if the
-
# attribute is +nil+ (default is +false+).
-
# * <tt>:allow_blank</tt> - If set to +true+, skips this validation if the
-
# attribute is blank (default is +false+).
-
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
-
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
-
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
-
# proc or string should return or evaluate to a +true+ or +false+ value.
-
# * <tt>:unless</tt> - Specifies a method, proc or string to call to
-
# determine if the validation should ot occur (e.g. <tt>unless: :skip_validation</tt>,
-
# or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The
-
# method, proc or string should return or evaluate to a +true+ or +false+
-
# value.
-
#
-
# === Concurrency and integrity
-
#
-
# Using this validation method in conjunction with ActiveRecord::Base#save
-
# does not guarantee the absence of duplicate record insertions, because
-
# uniqueness checks on the application level are inherently prone to race
-
# conditions. For example, suppose that two users try to post a Comment at
-
# the same time, and a Comment's title must be unique. At the database-level,
-
# the actions performed by these users could be interleaved in the following manner:
-
#
-
# User 1 | User 2
-
# ------------------------------------+--------------------------------------
-
# # User 1 checks whether there's |
-
# # already a comment with the title |
-
# # 'My Post'. This is not the case. |
-
# SELECT * FROM comments |
-
# WHERE title = 'My Post' |
-
# |
-
# | # User 2 does the same thing and also
-
# | # infers that his title is unique.
-
# | SELECT * FROM comments
-
# | WHERE title = 'My Post'
-
# |
-
# # User 1 inserts his comment. |
-
# INSERT INTO comments |
-
# (title, content) VALUES |
-
# ('My Post', 'hi!') |
-
# |
-
# | # User 2 does the same thing.
-
# | INSERT INTO comments
-
# | (title, content) VALUES
-
# | ('My Post', 'hello!')
-
# |
-
# | # ^^^^^^
-
# | # Boom! We now have a duplicate
-
# | # title!
-
#
-
# This could even happen if you use transactions with the 'serializable'
-
# isolation level. The best way to work around this problem is to add a unique
-
# index to the database table using
-
# ActiveRecord::ConnectionAdapters::SchemaStatements#add_index. In the
-
# rare case that a race condition occurs, the database will guarantee
-
# the field's uniqueness.
-
#
-
# When the database catches such a duplicate insertion,
-
# ActiveRecord::Base#save will raise an ActiveRecord::StatementInvalid
-
# exception. You can either choose to let this error propagate (which
-
# will result in the default Rails exception page being shown), or you
-
# can catch it and restart the transaction (e.g. by telling the user
-
# that the title already exists, and asking him to re-enter the title).
-
# This technique is also known as optimistic concurrency control:
-
# http://en.wikipedia.org/wiki/Optimistic_concurrency_control.
-
#
-
# The bundled ActiveRecord::ConnectionAdapters distinguish unique index
-
# constraint errors from other types of database errors by throwing an
-
# ActiveRecord::RecordNotUnique exception. For other adapters you will
-
# have to parse the (database-specific) exception message to detect such
-
# a case.
-
#
-
# The following bundled adapters throw the ActiveRecord::RecordNotUnique exception:
-
#
-
# * ActiveRecord::ConnectionAdapters::MysqlAdapter.
-
# * ActiveRecord::ConnectionAdapters::Mysql2Adapter.
-
# * ActiveRecord::ConnectionAdapters::SQLite3Adapter.
-
# * ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.
-
1
def validates_uniqueness_of(*attr_names)
-
validates_with UniquenessValidator, _merge_attributes(attr_names)
-
end
-
end
-
end
-
end
-
1
module ActiveRecord
-
1
module VERSION #:nodoc:
-
1
MAJOR = 4
-
1
MINOR = 0
-
1
TINY = 0
-
1
PRE = "beta"
-
-
1
STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
-
end
-
end
-
#--
-
# Copyright (c) 2005-2012 David Heinemeier Hansson
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining
-
# a copy of this software and associated documentation files (the
-
# "Software"), to deal in the Software without restriction, including
-
# without limitation the rights to use, copy, modify, merge, publish,
-
# distribute, sublicense, and/or sell copies of the Software, and to
-
# permit persons to whom the Software is furnished to do so, subject to
-
# the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
#++
-
-
1
require 'securerandom'
-
1
require "active_support/dependencies/autoload"
-
1
require "active_support/version"
-
1
require "active_support/logger"
-
1
require "active_support/lazy_load_hooks"
-
-
1
module ActiveSupport
-
1
extend ActiveSupport::Autoload
-
-
1
autoload :Concern
-
1
autoload :Dependencies
-
1
autoload :DescendantsTracker
-
1
autoload :FileUpdateChecker
-
1
autoload :LogSubscriber
-
1
autoload :Notifications
-
-
1
eager_autoload do
-
1
autoload :BacktraceCleaner
-
1
autoload :BasicObject
-
1
autoload :Benchmarkable
-
1
autoload :Cache
-
1
autoload :Callbacks
-
1
autoload :Configurable
-
1
autoload :Deprecation
-
1
autoload :Gzip
-
1
autoload :Inflector
-
1
autoload :JSON
-
1
autoload :KeyGenerator
-
1
autoload :MessageEncryptor
-
1
autoload :MessageVerifier
-
1
autoload :Multibyte
-
1
autoload :OptionMerger
-
1
autoload :OrderedHash
-
1
autoload :OrderedOptions
-
1
autoload :StringInquirer
-
1
autoload :TaggedLogging
-
1
autoload :XmlMini
-
end
-
-
1
autoload :Rescuable
-
1
autoload :SafeBuffer, "active_support/core_ext/string/output_safety"
-
1
autoload :TestCase
-
end
-
-
1
autoload :I18n, "active_support/i18n"
-
1
module ActiveSupport
-
# Backtraces often include many lines that are not relevant for the context
-
# under review. This makes it hard to find the signal amongst the backtrace
-
# noise, and adds debugging time. With a BacktraceCleaner, filters and
-
# silencers are used to remove the noisy lines, so that only the most relevant
-
# lines remain.
-
#
-
# Filters are used to modify lines of data, while silencers are used to remove
-
# lines entirely. The typical filter use case is to remove lengthy path
-
# information from the start of each line, and view file paths relevant to the
-
# app directory instead of the file system root. The typical silencer use case
-
# is to exclude the output of a noisy library from the backtrace, so that you
-
# can focus on the rest.
-
#
-
# bc = BacktraceCleaner.new
-
# bc.add_filter { |line| line.gsub(Rails.root, '') }
-
# bc.add_silencer { |line| line =~ /mongrel|rubygems/ }
-
# bc.clean(exception.backtrace) # will strip the Rails.root prefix and skip any lines from mongrel or rubygems
-
#
-
# To reconfigure an existing BacktraceCleaner (like the default one in Rails)
-
# and show as much data as possible, you can always call
-
# <tt>BacktraceCleaner#remove_silencers!</tt>, which will restore the
-
# backtrace to a pristine state. If you need to reconfigure an existing
-
# BacktraceCleaner so that it does not filter or modify the paths of any lines
-
# of the backtrace, you can call BacktraceCleaner#remove_filters! These two
-
# methods will give you a completely untouched backtrace.
-
#
-
# Inspired by the Quiet Backtrace gem by Thoughtbot.
-
1
class BacktraceCleaner
-
1
def initialize
-
5
@filters, @silencers = [], []
-
end
-
-
# Returns the backtrace after all filters and silencers have been run
-
# against it. Filters run first, then silencers.
-
1
def clean(backtrace, kind = :silent)
-
5
filtered = filter_backtrace(backtrace)
-
-
5
case kind
-
when :silent
-
5
silence(filtered)
-
when :noise
-
noise(filtered)
-
else
-
filtered
-
end
-
end
-
1
alias :filter :clean
-
-
# Adds a filter from the block provided. Each line in the backtrace will be
-
# mapped against this filter.
-
#
-
# # Will turn "/my/rails/root/app/models/person.rb" into "/app/models/person.rb"
-
# backtrace_cleaner.add_filter { |line| line.gsub(Rails.root, '') }
-
1
def add_filter(&block)
-
4
@filters << block
-
end
-
-
# Adds a silencer from the block provided. If the silencer returns +true+
-
# for a given line, it will be excluded from the clean backtrace.
-
#
-
# # Will reject all lines that include the word "mongrel", like "/gems/mongrel/server.rb" or "/app/my_mongrel_server/rb"
-
# backtrace_cleaner.add_silencer { |line| line =~ /mongrel/ }
-
1
def add_silencer(&block)
-
2
@silencers << block
-
end
-
-
# Will remove all silencers, but leave in the filters. This is useful if
-
# your context of debugging suddenly expands as you suspect a bug in one of
-
# the libraries you use.
-
1
def remove_silencers!
-
@silencers = []
-
end
-
-
1
def remove_filters!
-
1
@filters = []
-
end
-
-
1
private
-
1
def filter_backtrace(backtrace)
-
5
@filters.each do |f|
-
7
backtrace = backtrace.map { |line| f.call(line) }
-
end
-
-
5
backtrace
-
end
-
-
1
def silence(backtrace)
-
5
@silencers.each do |s|
-
6
backtrace = backtrace.reject { |line| s.call(line) }
-
end
-
-
5
backtrace
-
end
-
-
1
def noise(backtrace)
-
@silencers.each do |s|
-
backtrace = backtrace.select { |line| s.call(line) }
-
end
-
-
backtrace
-
end
-
end
-
end
-
1
module ActiveSupport
-
# A class with no predefined methods that behaves similarly to Builder's
-
# BlankSlate. Used for proxy classes.
-
1
class BasicObject < ::BasicObject
-
1
undef_method :==
-
1
undef_method :equal?
-
-
# Let ActiveSupport::BasicObject at least raise exceptions.
-
1
def raise(*args)
-
1
::Object.send(:raise, *args)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/benchmark'
-
1
require 'active_support/core_ext/hash/keys'
-
-
1
module ActiveSupport
-
1
module Benchmarkable
-
# Allows you to measure the execution time of a block in a template and
-
# records the result to the log. Wrap this block around expensive operations
-
# or possible bottlenecks to get a time reading for the operation. For
-
# example, let's say you thought your file processing method was taking too
-
# long; you could wrap it in a benchmark block.
-
#
-
# <% benchmark 'Process data files' do %>
-
# <%= expensive_files_operation %>
-
# <% end %>
-
#
-
# That would add something like "Process data files (345.2ms)" to the log,
-
# which you can then use to compare timings when optimizing your code.
-
#
-
# You may give an optional logger level (<tt>:debug</tt>, <tt>:info</tt>,
-
# <tt>:warn</tt>, <tt>:error</tt>) as the <tt>:level</tt> option. The
-
# default logger level value is <tt>:info</tt>.
-
#
-
# <% benchmark 'Low-level files', level: :debug do %>
-
# <%= lowlevel_files_operation %>
-
# <% end %>
-
#
-
# Finally, you can pass true as the third argument to silence all log
-
# activity (other than the timing information) from inside the block. This
-
# is great for boiling down a noisy block to just a single statement that
-
# produces one log line:
-
#
-
# <% benchmark 'Process data files', level: :info, silence: true do %>
-
# <%= expensive_and_chatty_files_operation %>
-
# <% end %>
-
1
def benchmark(message = "Benchmarking", options = {})
-
5
if logger
-
5
options.assert_valid_keys(:level, :silence)
-
5
options[:level] ||= :info
-
-
5
result = nil
-
10
ms = Benchmark.ms { result = options[:silence] ? silence { yield } : yield }
-
4
logger.send(options[:level], '%s (%.1fms)' % [ message, ms ])
-
4
result
-
else
-
yield
-
end
-
end
-
-
# Silence the logger during the execution of the block.
-
1
def silence
-
message = "ActiveSupport::Benchmarkable#silence is deprecated. It will be removed from Rails 4.1."
-
ActiveSupport::Deprecation.warn message
-
old_logger_level, logger.level = logger.level, ::Logger::ERROR if logger
-
yield
-
ensure
-
logger.level = old_logger_level if logger
-
end
-
end
-
end
-
1
require 'active_support/deprecation'
-
1
require 'active_support/logger'
-
-
1
module ActiveSupport
-
1
BufferedLogger = ActiveSupport::Deprecation::DeprecatedConstantProxy.new(
-
'BufferedLogger', '::ActiveSupport::Logger')
-
end
-
1
begin
-
1
require 'builder'
-
rescue LoadError => e
-
$stderr.puts "You don't have builder installed in your application. Please add it to your Gemfile and run bundle install"
-
raise e
-
end
-
1
require 'benchmark'
-
1
require 'zlib'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/array/wrap'
-
1
require 'active_support/core_ext/benchmark'
-
1
require 'active_support/core_ext/exception'
-
1
require 'active_support/core_ext/class/attribute_accessors'
-
1
require 'active_support/core_ext/numeric/bytes'
-
1
require 'active_support/core_ext/numeric/time'
-
1
require 'active_support/core_ext/object/to_param'
-
1
require 'active_support/core_ext/string/inflections'
-
-
1
module ActiveSupport
-
# See ActiveSupport::Cache::Store for documentation.
-
1
module Cache
-
1
autoload :FileStore, 'active_support/cache/file_store'
-
1
autoload :MemoryStore, 'active_support/cache/memory_store'
-
1
autoload :MemCacheStore, 'active_support/cache/mem_cache_store'
-
1
autoload :NullStore, 'active_support/cache/null_store'
-
-
# These options mean something to all cache implementations. Individual cache
-
# implementations may support additional options.
-
1
UNIVERSAL_OPTIONS = [:namespace, :compress, :compress_threshold, :expires_in, :race_condition_ttl]
-
-
1
module Strategy
-
1
autoload :LocalCache, 'active_support/cache/strategy/local_cache'
-
end
-
-
1
class << self
-
# Creates a new CacheStore object according to the given options.
-
#
-
# If no arguments are passed to this method, then a new
-
# ActiveSupport::Cache::MemoryStore object will be returned.
-
#
-
# If you pass a Symbol as the first argument, then a corresponding cache
-
# store class under the ActiveSupport::Cache namespace will be created.
-
# For example:
-
#
-
# ActiveSupport::Cache.lookup_store(:memory_store)
-
# # => returns a new ActiveSupport::Cache::MemoryStore object
-
#
-
# ActiveSupport::Cache.lookup_store(:mem_cache_store)
-
# # => returns a new ActiveSupport::Cache::MemCacheStore object
-
#
-
# Any additional arguments will be passed to the corresponding cache store
-
# class's constructor:
-
#
-
# ActiveSupport::Cache.lookup_store(:file_store, '/tmp/cache')
-
# # => same as: ActiveSupport::Cache::FileStore.new('/tmp/cache')
-
#
-
# If the first argument is not a Symbol, then it will simply be returned:
-
#
-
# ActiveSupport::Cache.lookup_store(MyOwnCacheStore.new)
-
# # => returns MyOwnCacheStore.new
-
1
def lookup_store(*store_option)
-
517
store, *parameters = *Array.wrap(store_option).flatten
-
-
517
case store
-
when Symbol
-
515
store_class_name = store.to_s.camelize
-
515
store_class =
-
begin
-
515
require "active_support/cache/#{store}"
-
rescue LoadError => e
-
raise "Could not find cache store adapter for #{store} (#{e})"
-
else
-
515
ActiveSupport::Cache.const_get(store_class_name)
-
end
-
515
store_class.new(*parameters)
-
when nil
-
1
ActiveSupport::Cache::MemoryStore.new
-
else
-
1
store
-
end
-
end
-
-
1
def expand_cache_key(key, namespace = nil)
-
16
expanded_cache_key = namespace ? "#{namespace}/" : ""
-
-
16
if prefix = ENV["RAILS_CACHE_ID"] || ENV["RAILS_APP_VERSION"]
-
8
expanded_cache_key << "#{prefix}/"
-
end
-
-
16
expanded_cache_key << retrieve_cache_key(key)
-
16
expanded_cache_key
-
end
-
-
1
private
-
-
1
def retrieve_cache_key(key)
-
case
-
2
when key.respond_to?(:cache_key) then key.cache_key
-
25
when key.is_a?(Array) then key.map { |element| retrieve_cache_key(element) }.to_param
-
2
when key.respond_to?(:to_a) then retrieve_cache_key(key.to_a)
-
21
else key.to_param
-
34
end.to_s
-
end
-
end
-
-
# An abstract cache store class. There are multiple cache store
-
# implementations, each having its own additional features. See the classes
-
# under the ActiveSupport::Cache module, e.g.
-
# ActiveSupport::Cache::MemCacheStore. MemCacheStore is currently the most
-
# popular cache store for large production websites.
-
#
-
# Some implementations may not support all methods beyond the basic cache
-
# methods of +fetch+, +write+, +read+, +exist?+, and +delete+.
-
#
-
# ActiveSupport::Cache::Store can store any serializable Ruby object.
-
#
-
# cache = ActiveSupport::Cache::MemoryStore.new
-
#
-
# cache.read('city') # => nil
-
# cache.write('city', "Duckburgh")
-
# cache.read('city') # => "Duckburgh"
-
#
-
# Keys are always translated into Strings and are case sensitive. When an
-
# object is specified as a key and has a +cache_key+ method defined, this
-
# method will be called to define the key. Otherwise, the +to_param+
-
# method will be called. Hashes and Arrays can also be used as keys. The
-
# elements will be delimited by slashes, and the elements within a Hash
-
# will be sorted by key so they are consistent.
-
#
-
# cache.read('city') == cache.read(:city) # => true
-
#
-
# Nil values can be cached.
-
#
-
# If your cache is on a shared infrastructure, you can define a namespace
-
# for your cache entries. If a namespace is defined, it will be prefixed on
-
# to every key. The namespace can be either a static value or a Proc. If it
-
# is a Proc, it will be invoked when each key is evaluated so that you can
-
# use application logic to invalidate keys.
-
#
-
# cache.namespace = -> { @last_mod_time } # Set the namespace to a variable
-
# @last_mod_time = Time.now # Invalidate the entire cache by changing namespace
-
#
-
# Caches can also store values in a compressed format to save space and
-
# reduce time spent sending data. Since there is overhead, values must be
-
# large enough to warrant compression. To turn on compression either pass
-
# <tt>compress: true</tt> in the initializer or as an option to +fetch+
-
# or +write+. To specify the threshold at which to compress values, set the
-
# <tt>:compress_threshold</tt> option. The default threshold is 16K.
-
1
class Store
-
-
1
cattr_accessor :logger, :instance_writer => true
-
-
1
attr_reader :silence, :options
-
1
alias :silence? :silence
-
-
# Create a new cache. The options will be passed to any write method calls
-
# except for <tt>:namespace</tt> which can be used to set the global
-
# namespace for the cache.
-
1
def initialize(options = nil)
-
541
@options = options ? options.dup : {}
-
end
-
-
# Silence the logger.
-
1
def silence!
-
149
@silence = true
-
149
self
-
end
-
-
# Silence the logger within a block.
-
1
def mute
-
3
previous_silence, @silence = defined?(@silence) && @silence, true
-
3
yield
-
ensure
-
3
@silence = previous_silence
-
end
-
-
# Set to +true+ if cache stores should be instrumented.
-
# Default is +false+.
-
1
def self.instrument=(boolean)
-
Thread.current[:instrument_cache_store] = boolean
-
end
-
-
1
def self.instrument
-
1397
Thread.current[:instrument_cache_store] || false
-
end
-
-
# Fetches data from the cache, using the given key. If there is data in
-
# the cache with the given key, then that data is returned.
-
#
-
# If there is no such data in the cache (a cache miss), then +nil+ will be
-
# returned. However, if a block has been passed, that block will be passed
-
# the key and executed in the event of a cache miss. The return value of the
-
# block will be written to the cache under the given cache key, and that
-
# return value will be returned.
-
#
-
# cache.write('today', 'Monday')
-
# cache.fetch('today') # => "Monday"
-
#
-
# cache.fetch('city') # => nil
-
# cache.fetch('city') do
-
# 'Duckburgh'
-
# end
-
# cache.fetch('city') # => "Duckburgh"
-
#
-
# You may also specify additional options via the +options+ argument.
-
# Setting <tt>force: true</tt> will force a cache miss:
-
#
-
# cache.write('today', 'Monday')
-
# cache.fetch('today', force: true) # => nil
-
#
-
# Setting <tt>:compress</tt> will store a large cache entry set by the call
-
# in a compressed format.
-
#
-
# Setting <tt>:expires_in</tt> will set an expiration time on the cache.
-
# All caches support auto-expiring content after a specified number of
-
# seconds. This value can be specified as an option to the constructor
-
# (in which case all entries will be affected), or it can be supplied to
-
# the +fetch+ or +write+ method to effect just one entry.
-
#
-
# cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 5.minutes)
-
# cache.write(key, value, expires_in: 1.minute) # Set a lower value for one entry
-
#
-
# Setting <tt>:race_condition_ttl</tt> is very useful in situations where
-
# a cache entry is used very frequently and is under heavy load. If a
-
# cache expires and due to heavy load seven different processes will try
-
# to read data natively and then they all will try to write to cache. To
-
# avoid that case the first process to find an expired cache entry will
-
# bump the cache expiration time by the value set in <tt>:race_condition_ttl</tt>.
-
# Yes, this process is extending the time for a stale value by another few
-
# seconds. Because of extended life of the previous cache, other processes
-
# will continue to use slightly stale data for a just a big longer. In the
-
# meantime that first process will go ahead and will write into cache the
-
# new value. After that all the processes will start getting new value.
-
# The key is to keep <tt>:race_condition_ttl</tt> small.
-
#
-
# If the process regenerating the entry errors out, the entry will be
-
# regenerated after the specified number of seconds. Also note that the
-
# life of stale cache is extended only if it expired recently. Otherwise
-
# a new value is generated and <tt>:race_condition_ttl</tt> does not play
-
# any role.
-
#
-
# # Set all values to expire after one minute.
-
# cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 1.minute)
-
#
-
# cache.write('foo', 'original value')
-
# val_1 = nil
-
# val_2 = nil
-
# sleep 60
-
#
-
# Thread.new do
-
# val_1 = cache.fetch('foo', race_condition_ttl: 10) do
-
# sleep 1
-
# 'new value 1'
-
# end
-
# end
-
#
-
# Thread.new do
-
# val_2 = cache.fetch('foo', race_condition_ttl: 10) do
-
# 'new value 2'
-
# end
-
# end
-
#
-
# # val_1 => "new value 1"
-
# # val_2 => "original value"
-
# # sleep 10 # First thread extend the life of cache by another 10 seconds
-
# # cache.fetch('foo') => "new value 1"
-
#
-
# Other options will be handled by the specific cache store implementation.
-
# Internally, #fetch calls #read_entry, and calls #write_entry on a cache
-
# miss. +options+ will be passed to the #read and #write calls.
-
#
-
# For example, MemCacheStore's #write method supports the +:raw+
-
# option, which tells the memcached server to store all values as strings.
-
# We can use this option with #fetch too:
-
#
-
# cache = ActiveSupport::Cache::MemCacheStore.new
-
# cache.fetch("foo", force: true, raw: true) do
-
# :bar
-
# end
-
# cache.fetch('foo') # => "bar"
-
1
def fetch(name, options = nil)
-
235
if block_given?
-
131
options = merged_options(options)
-
131
key = namespaced_key(name, options)
-
131
unless options[:force]
-
128
entry = instrument(:read, name, options) do |payload|
-
128
payload[:super_operation] = :fetch if payload
-
128
read_entry(key, options)
-
end
-
end
-
131
if entry && entry.expired?
-
9
race_ttl = options[:race_condition_ttl].to_i
-
9
if race_ttl && (Time.now - entry.expires_at <= race_ttl)
-
# When an entry has :race_condition_ttl defined, put the stale entry back into the cache
-
# for a brief period while the entry is begin recalculated.
-
6
entry.expires_at = Time.now + race_ttl
-
6
write_entry(key, entry, :expires_in => race_ttl * 2)
-
else
-
3
delete_entry(key, options)
-
end
-
9
entry = nil
-
end
-
-
131
if entry
-
9
instrument(:fetch_hit, name, options) { |payload| }
-
9
entry.value
-
else
-
122
result = instrument(:generate, name, options) do |payload|
-
122
yield(name)
-
end
-
119
write(name, result, options)
-
119
result
-
end
-
else
-
104
read(name, options)
-
end
-
end
-
-
# Fetches data from the cache, using the given key. If there is data in
-
# the cache with the given key, then that data is returned. Otherwise,
-
# +nil+ is returned.
-
#
-
# Options are passed to the underlying cache implementation.
-
1
def read(name, options = nil)
-
340
options = merged_options(options)
-
340
key = namespaced_key(name, options)
-
340
instrument(:read, name, options) do |payload|
-
340
entry = read_entry(key, options)
-
340
if entry
-
321
if entry.expired?
-
6
delete_entry(key, options)
-
6
payload[:hit] = false if payload
-
6
nil
-
else
-
315
payload[:hit] = true if payload
-
315
entry.value
-
end
-
else
-
19
payload[:hit] = false if payload
-
19
nil
-
end
-
end
-
end
-
-
# Read multiple values at once from the cache. Options can be passed
-
# in the last argument.
-
#
-
# Some cache implementation may optimize this method.
-
#
-
# Returns a hash mapping the names provided to the values found.
-
1
def read_multi(*names)
-
5
options = names.extract_options!
-
5
options = merged_options(options)
-
5
results = {}
-
5
names.each do |name|
-
9
key = namespaced_key(name, options)
-
9
entry = read_entry(key, options)
-
9
if entry
-
9
if entry.expired?
-
2
delete_entry(key, options)
-
else
-
7
results[name] = entry.value
-
end
-
end
-
end
-
5
results
-
end
-
-
# Writes the value to the cache, with the key.
-
#
-
# Options are passed to the underlying cache implementation.
-
1
def write(name, value, options = nil)
-
412
options = merged_options(options)
-
412
instrument(:write, name, options) do |payload|
-
412
entry = Entry.new(value, options)
-
412
write_entry(namespaced_key(name, options), entry, options)
-
end
-
end
-
-
# Deletes an entry in the cache. Returns +true+ if an entry is deleted.
-
#
-
# Options are passed to the underlying cache implementation.
-
1
def delete(name, options = nil)
-
115
options = merged_options(options)
-
115
instrument(:delete, name) do |payload|
-
115
delete_entry(namespaced_key(name, options), options)
-
end
-
end
-
-
# Return +true+ if the cache contains an entry for the given key.
-
#
-
# Options are passed to the underlying cache implementation.
-
1
def exist?(name, options = nil)
-
50
options = merged_options(options)
-
50
instrument(:exist?, name) do |payload|
-
50
entry = read_entry(namespaced_key(name, options), options)
-
50
entry && !entry.expired?
-
end
-
end
-
-
# Delete all entries with keys matching the pattern.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
1
def delete_matched(matcher, options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support delete_matched")
-
end
-
-
# Increment an integer value in the cache.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
1
def increment(name, amount = 1, options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support increment")
-
end
-
-
# Decrement an integer value in the cache.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
1
def decrement(name, amount = 1, options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support decrement")
-
end
-
-
# Cleanup the cache by removing expired entries.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
1
def cleanup(options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support cleanup")
-
end
-
-
# Clear the entire cache. Be careful with this method since it could
-
# affect other processes if shared cache is being used.
-
#
-
# Options are passed to the underlying cache implementation.
-
#
-
# All implementations may not support this method.
-
1
def clear(options = nil)
-
raise NotImplementedError.new("#{self.class.name} does not support clear")
-
end
-
-
1
protected
-
# Add the namespace defined in the options to a pattern designed to
-
# match keys. Implementations that support delete_matched should call
-
# this method to translate a pattern that matches names into one that
-
# matches namespaced keys.
-
1
def key_matcher(pattern, options)
-
5
prefix = options[:namespace].is_a?(Proc) ? options[:namespace].call : options[:namespace]
-
5
if prefix
-
2
source = pattern.source
-
2
if source.start_with?('^')
-
1
source = source[1, source.length]
-
else
-
1
source = ".*#{source[0, source.length]}"
-
end
-
2
Regexp.new("^#{Regexp.escape(prefix)}:#{source}", pattern.options)
-
else
-
3
pattern
-
end
-
end
-
-
# Read an entry from the cache implementation. Subclasses must implement
-
# this method.
-
1
def read_entry(key, options) # :nodoc:
-
raise NotImplementedError.new
-
end
-
-
# Write an entry to the cache implementation. Subclasses must implement
-
# this method.
-
1
def write_entry(key, entry, options) # :nodoc:
-
raise NotImplementedError.new
-
end
-
-
# Delete an entry from the cache implementation. Subclasses must
-
# implement this method.
-
1
def delete_entry(key, options) # :nodoc:
-
raise NotImplementedError.new
-
end
-
-
1
private
-
# Merge the default options with ones specific to a method call.
-
1
def merged_options(call_options) # :nodoc:
-
1286
if call_options
-
400
options.merge(call_options)
-
else
-
886
options.dup
-
end
-
end
-
-
# Expand key to be a consistent string value. Invoke +cache_key+ if
-
# object responds to +cache_key+. Otherwise, +to_param+ method will be
-
# called. If the key is a Hash, then keys will be sorted alphabetically.
-
1
def expanded_key(key) # :nodoc:
-
1282
return key.cache_key.to_s if key.respond_to?(:cache_key)
-
-
1279
case key
-
when Array
-
3
if key.size > 1
-
9
key = key.collect{|element| expanded_key(element)}
-
else
-
key = key.first
-
end
-
when Hash
-
15
key = key.sort_by { |k,_| k.to_s }.collect{|k,v| "#{k}=#{v}"}
-
end
-
-
1279
key.to_param
-
end
-
-
# Prefix a key with the namespace. Namespace and key will be delimited
-
# with a colon.
-
1
def namespaced_key(key, options)
-
1276
key = expanded_key(key)
-
1276
namespace = options[:namespace] if options
-
1276
prefix = namespace.is_a?(Proc) ? namespace.call : namespace
-
1276
key = "#{prefix}:#{key}" if prefix
-
1276
key
-
end
-
-
1
def instrument(operation, key, options = nil)
-
1397
log(operation, key, options)
-
-
1397
if self.class.instrument
-
payload = { :key => key }
-
payload.merge!(options) if options.is_a?(Hash)
-
ActiveSupport::Notifications.instrument("cache_#{operation}.active_support", payload){ yield(payload) }
-
else
-
1397
yield(nil)
-
end
-
end
-
-
1
def log(operation, key, options = nil)
-
1397
return unless logger && logger.debug? && !silence?
-
353
logger.debug("Cache #{operation}: #{key}#{options.blank? ? "" : " (#{options.inspect})"}")
-
end
-
end
-
-
# This class is used to represent cache entries. Cache entries have a value and an optional
-
# expiration time. The expiration time is used to support the :race_condition_ttl option
-
# on the cache.
-
#
-
# Since cache entries in most instances will be serialized, the internals of this class are highly optimized
-
# using short instance variable names that are lazily defined.
-
1
class Entry # :nodoc:
-
1
DEFAULT_COMPRESS_LIMIT = 16.kilobytes
-
-
# Create a new cache entry for the specified value. Options supported are
-
# +:compress+, +:compress_threshold+, and +:expires_in+.
-
1
def initialize(value, options = {})
-
671
if should_compress?(value, options)
-
4
@v = compress(value)
-
4
@c = true
-
else
-
667
@v = value
-
end
-
671
if expires_in = options[:expires_in]
-
388
@x = (Time.now + expires_in).to_i
-
end
-
end
-
-
1
def value
-
709
convert_version_3_entry! if defined?(@value)
-
709
compressed? ? uncompress(@v) : @v
-
end
-
-
# Check if the entry is expired. The +expires_in+ parameter can override
-
# the value set when the entry was created.
-
1
def expired?
-
410
convert_version_3_entry! if defined?(@value)
-
410
if defined?(@x)
-
189
@x && @x < Time.now.to_i
-
else
-
221
false
-
end
-
end
-
-
1
def expires_at
-
13
Time.at(@x) if defined?(@x)
-
end
-
-
1
def expires_at=(value)
-
10
@x = value.to_i
-
end
-
-
# Returns the size of the cached value. This could be less than
-
# <tt>value.size</tt> if the data is compressed.
-
1
def size
-
152
if defined?(@s)
-
5
@s
-
else
-
147
case value
-
when NilClass
-
5
0
-
when String
-
130
@v.bytesize
-
else
-
12
@s = Marshal.dump(@v).bytesize
-
end
-
end
-
end
-
-
# Duplicate the value in a class. This is used by cache implementations that don't natively
-
# serialize entries to protect against accidental cache modifications.
-
1
def dup_value!
-
85
convert_version_3_entry! if defined?(@value)
-
85
if @v && !compressed? && !(@v.is_a?(Numeric) || @v == true || @v == false)
-
68
if @v.is_a?(String)
-
67
@v = @v.dup
-
else
-
1
@v = Marshal.load(Marshal.dump(@v))
-
end
-
end
-
end
-
-
1
private
-
1
def should_compress?(value, options)
-
671
if value && options[:compress]
-
7
compress_threshold = options[:compress_threshold] || DEFAULT_COMPRESS_LIMIT
-
7
serialized_value_size = (value.is_a?(String) ? value : Marshal.dump(value)).bytesize
-
7
return true if serialized_value_size >= compress_threshold
-
end
-
667
false
-
end
-
-
1
def compressed?
-
788
defined?(@c) ? @c : false
-
end
-
-
1
def compress(value)
-
4
Zlib::Deflate.deflate(Marshal.dump(value))
-
end
-
-
1
def uncompress(value)
-
7
Marshal.load(Zlib::Inflate.inflate(value))
-
end
-
-
# The internals of this method changed between Rails 3.x and 4.0. This method provides the glue
-
# to ensure that cache entries created under the old version still work with the new class definition.
-
1
def convert_version_3_entry!
-
4
if defined?(@value)
-
4
@v = @value
-
4
remove_instance_variable(:@value)
-
end
-
4
if defined?(@compressed)
-
1
@c = @compressed
-
1
remove_instance_variable(:@compressed)
-
end
-
4
if defined?(@expires_in) && defined?(@created_at) && @expires_in && @created_at
-
1
@x = (@created_at + @expires_in).to_i
-
1
remove_instance_variable(:@created_at)
-
1
remove_instance_variable(:@expires_in)
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/file/atomic'
-
1
require 'active_support/core_ext/string/conversions'
-
1
require 'uri/common'
-
-
1
module ActiveSupport
-
1
module Cache
-
# A cache store implementation which stores everything on the filesystem.
-
#
-
# FileStore implements the Strategy::LocalCache strategy which implements
-
# an in-memory cache inside of a block.
-
1
class FileStore < Store
-
1
attr_reader :cache_path
-
-
1
DIR_FORMATTER = "%03X"
-
1
FILENAME_MAX_SIZE = 228 # max filename size on file system is 255, minus room for timestamp and random characters appended by Tempfile (used by atomic write)
-
1
EXCLUDED_DIRS = ['.', '..'].freeze
-
-
1
def initialize(cache_path, options = nil)
-
156
super(options)
-
156
@cache_path = cache_path.to_s
-
156
extend Strategy::LocalCache
-
end
-
-
1
def clear(options = nil)
-
8
root_dirs = Dir.entries(cache_path).reject {|f| (EXCLUDED_DIRS + [".gitkeep"]).include?(f)}
-
3
FileUtils.rm_r(root_dirs.collect{|f| File.join(cache_path, f)})
-
end
-
-
1
def cleanup(options = nil)
-
options = merged_options(options)
-
each_key(options) do |key|
-
entry = read_entry(key, options)
-
delete_entry(key, options) if entry && entry.expired?
-
end
-
end
-
-
1
def increment(name, amount = 1, options = nil)
-
2
file_name = key_file_path(namespaced_key(name, options))
-
2
lock_file(file_name) do
-
2
options = merged_options(options)
-
2
if num = read(name, options)
-
2
num = num.to_i + amount
-
2
write(name, num, options)
-
num
-
else
-
nil
-
end
-
end
-
end
-
-
1
def decrement(name, amount = 1, options = nil)
-
2
file_name = key_file_path(namespaced_key(name, options))
-
2
lock_file(file_name) do
-
2
options = merged_options(options)
-
2
if num = read(name, options)
-
2
num = num.to_i - amount
-
2
write(name, num, options)
-
num
-
else
-
nil
-
end
-
end
-
end
-
-
1
def delete_matched(matcher, options = nil)
-
2
options = merged_options(options)
-
2
instrument(:delete_matched, matcher.inspect) do
-
2
matcher = key_matcher(matcher, options)
-
2
search_dir(cache_path) do |path|
-
4
key = file_path_key(path)
-
4
delete_entry(key, options) if key.match(matcher)
-
end
-
end
-
end
-
-
1
protected
-
-
1
def read_entry(key, options)
-
55
file_name = key_file_path(key)
-
55
if File.exist?(file_name)
-
86
File.open(file_name) { |f| Marshal.load(f) }
-
end
-
rescue => e
-
1
logger.error("FileStoreError (#{e}): #{e.message}") if logger
-
1
nil
-
end
-
-
1
def write_entry(key, entry, options)
-
62
file_name = key_file_path(key)
-
62
ensure_cache_path(File.dirname(file_name))
-
121
File.atomic_write(file_name, cache_path) {|f| Marshal.dump(entry, f)}
-
56
true
-
end
-
-
1
def delete_entry(key, options)
-
10
file_name = key_file_path(key)
-
10
if File.exist?(file_name)
-
10
begin
-
10
File.delete(file_name)
-
10
delete_empty_directories(File.dirname(file_name))
-
10
true
-
rescue => e
-
# Just in case the error was caused by another process deleting the file first.
-
raise e if File.exist?(file_name)
-
false
-
end
-
end
-
end
-
-
1
private
-
# Lock a file for a block so only one process can modify it at a time.
-
1
def lock_file(file_name, &block) # :nodoc:
-
4
if File.exist?(file_name)
-
4
File.open(file_name, 'r+') do |f|
-
4
begin
-
4
f.flock File::LOCK_EX
-
4
yield
-
ensure
-
4
f.flock File::LOCK_UN
-
end
-
end
-
else
-
yield
-
end
-
end
-
-
# Translate a key into a file path.
-
1
def key_file_path(key)
-
135
fname = URI.encode_www_form_component(key)
-
135
hash = Zlib.adler32(fname)
-
135
hash, dir_1 = hash.divmod(0x1000)
-
135
dir_2 = hash.modulo(0x1000)
-
135
fname_paths = []
-
-
# Make sure file name doesn't exceed file system limits.
-
begin
-
139
fname_paths << fname[0, FILENAME_MAX_SIZE]
-
139
fname = fname[FILENAME_MAX_SIZE..-1]
-
135
end until fname.blank?
-
-
135
File.join(cache_path, DIR_FORMATTER % dir_1, DIR_FORMATTER % dir_2, *fname_paths)
-
end
-
-
# Translate a file path into a key.
-
1
def file_path_key(path)
-
6
fname = path[cache_path.to_s.size..-1].split(File::SEPARATOR, 4).last
-
6
URI.decode_www_form_component(fname, Encoding::UTF_8)
-
end
-
-
# Delete empty directories in the cache.
-
1
def delete_empty_directories(dir)
-
20
return if dir == cache_path
-
70
if Dir.entries(dir).reject {|f| EXCLUDED_DIRS.include?(f)}.empty?
-
10
File.delete(dir) rescue nil
-
10
delete_empty_directories(File.dirname(dir))
-
end
-
end
-
-
# Make sure a file path's directories exist.
-
1
def ensure_cache_path(path)
-
62
FileUtils.makedirs(path) unless File.exist?(path)
-
end
-
-
1
def search_dir(dir, &callback)
-
10
return if !File.exist?(dir)
-
9
Dir.foreach(dir) do |d|
-
30
next if EXCLUDED_DIRS.include?(d)
-
12
name = File.join(dir, d)
-
12
if File.directory?(name)
-
8
search_dir(name, &callback)
-
else
-
4
callback.call name
-
end
-
end
-
end
-
end
-
end
-
end
-
1
begin
-
1
require 'dalli'
-
rescue LoadError => e
-
$stderr.puts "You don't have dalli installed in your application. Please add it to your Gemfile and run bundle install"
-
raise e
-
end
-
-
1
require 'digest/md5'
-
-
1
module ActiveSupport
-
1
module Cache
-
# A cache store implementation which stores data in Memcached:
-
# http://memcached.org/
-
#
-
# This is currently the most popular cache store for production websites.
-
#
-
# Special features:
-
# - Clustering and load balancing. One can specify multiple memcached servers,
-
# and MemCacheStore will load balance between all available servers. If a
-
# server goes down, then MemCacheStore will ignore it until it comes back up.
-
#
-
# MemCacheStore implements the Strategy::LocalCache strategy which implements
-
# an in-memory cache inside of a block.
-
1
class MemCacheStore < Store
-
1
ESCAPE_KEY_CHARS = /[\x00-\x20%\x7F-\xFF]/n
-
-
1
def self.build_mem_cache(*addresses)
-
305
addresses = addresses.flatten
-
305
options = addresses.extract_options!
-
305
addresses = ["localhost:11211"] if addresses.empty?
-
305
Dalli::Client.new(addresses, options)
-
end
-
-
# Creates a new MemCacheStore object, with the given memcached server
-
# addresses. Each address is either a host name, or a host-with-port string
-
# in the form of "host_name:port". For example:
-
#
-
# ActiveSupport::Cache::MemCacheStore.new("localhost", "server-downstairs.localnetwork:8229")
-
#
-
# If no addresses are specified, then MemCacheStore will connect to
-
# localhost port 11211 (the default memcached port).
-
#
-
# Instead of addresses one can pass in a MemCache-like object. For example:
-
#
-
# require 'memcached' # gem install memcached; uses C bindings to libmemcached
-
# ActiveSupport::Cache::MemCacheStore.new(Memcached::Rails.new("localhost:11211"))
-
1
def initialize(*addresses)
-
307
addresses = addresses.flatten
-
307
options = addresses.extract_options!
-
307
super(options)
-
-
307
if addresses.first.respond_to?(:get)
-
2
@data = addresses.first
-
else
-
305
mem_cache_options = options.dup
-
1830
UNIVERSAL_OPTIONS.each{|name| mem_cache_options.delete(name)}
-
305
@data = self.class.build_mem_cache(*(addresses + [mem_cache_options]))
-
end
-
-
307
extend Strategy::LocalCache
-
307
extend LocalCacheWithRaw
-
end
-
-
# Reads multiple values from the cache using a single call to the
-
# servers for all keys. Options can be passed in the last argument.
-
1
def read_multi(*names)
-
3
options = names.extract_options!
-
3
options = merged_options(options)
-
8
keys_to_names = Hash[names.map{|name| [escape_key(namespaced_key(name, options)), name]}]
-
3
raw_values = @data.get_multi(keys_to_names.keys, :raw => true)
-
3
values = {}
-
3
raw_values.each do |key, value|
-
5
entry = deserialize_entry(value)
-
5
values[keys_to_names[key]] = entry.value unless entry.expired?
-
end
-
3
values
-
end
-
-
# Increment a cached value. This method uses the memcached incr atomic
-
# operator and can only be used on values written with the :raw option.
-
# Calling it on a value not stored with :raw will initialize that value
-
# to zero.
-
1
def increment(name, amount = 1, options = nil) # :nodoc:
-
105
options = merged_options(options)
-
105
instrument(:increment, name, :amount => amount) do
-
105
@data.incr(escape_key(namespaced_key(name, options)), amount)
-
end
-
rescue Dalli::DalliError
-
logger.error("DalliError (#{e}): #{e.message}") if logger
-
nil
-
end
-
-
# Decrement a cached value. This method uses the memcached decr atomic
-
# operator and can only be used on values written with the :raw option.
-
# Calling it on a value not stored with :raw will initialize that value
-
# to zero.
-
1
def decrement(name, amount = 1, options = nil) # :nodoc:
-
105
options = merged_options(options)
-
105
instrument(:decrement, name, :amount => amount) do
-
105
@data.decr(escape_key(namespaced_key(name, options)), amount)
-
end
-
rescue Dalli::DalliError
-
logger.error("DalliError (#{e}): #{e.message}") if logger
-
nil
-
end
-
-
# Clear the entire cache on all memcached servers. This method should
-
# be used with care when shared cache is being used.
-
1
def clear(options = nil)
-
154
@data.flush_all
-
rescue Dalli::DalliError => e
-
logger.error("DalliError (#{e}): #{e.message}") if logger
-
nil
-
end
-
-
# Get the statistics from the memcached servers.
-
1
def stats
-
@data.stats
-
end
-
-
1
protected
-
# Read an entry from the cache.
-
1
def read_entry(key, options) # :nodoc:
-
358
deserialize_entry(@data.get(escape_key(key), options))
-
rescue Dalli::DalliError => e
-
logger.error("DalliError (#{e}): #{e.message}") if logger
-
nil
-
end
-
-
# Write an entry to the cache.
-
1
def write_entry(key, entry, options) # :nodoc:
-
261
method = options && options[:unless_exist] ? :add : :set
-
261
value = options[:raw] ? entry.value.to_s : entry
-
261
expires_in = options[:expires_in].to_i
-
261
if expires_in > 0 && !options[:raw]
-
# Set the memcache expire a few minutes in the future to support race condition ttls on read
-
47
expires_in += 5.minutes
-
end
-
261
@data.send(method, escape_key(key), value, expires_in, options)
-
rescue Dalli::DalliError => e
-
logger.error("DalliError (#{e}): #{e.message}") if logger
-
false
-
end
-
-
# Delete an entry from the cache.
-
1
def delete_entry(key, options) # :nodoc:
-
109
@data.delete(escape_key(key))
-
rescue Dalli::DalliError => e
-
logger.error("DalliError (#{e}): #{e.message}") if logger
-
false
-
end
-
-
1
private
-
-
# Memcache keys are binaries. So we need to force their encoding to binary
-
# before applying the regular expression to ensure we are escaping all
-
# characters properly.
-
1
def escape_key(key)
-
943
key = key.to_s.dup
-
943
key = key.force_encoding("BINARY")
-
977
key = key.gsub(ESCAPE_KEY_CHARS){ |match| "%#{match.getbyte(0).to_s(16).upcase}" }
-
943
key = "#{key[0, 213]}:md5:#{Digest::MD5.hexdigest(key)}" if key.size > 250
-
943
key
-
end
-
-
1
def deserialize_entry(raw_value)
-
365
if raw_value
-
254
entry = Marshal.load(raw_value) rescue raw_value
-
254
entry.is_a?(Entry) ? entry : Entry.new(entry)
-
else
-
nil
-
end
-
end
-
-
# Provide support for raw values in the local cache strategy.
-
1
module LocalCacheWithRaw # :nodoc:
-
1
protected
-
1
def read_entry(key, options)
-
367
entry = super
-
367
if options[:raw] && local_cache && entry
-
2
entry = deserialize_entry(entry.value)
-
end
-
367
entry
-
end
-
-
1
def write_entry(key, entry, options) # :nodoc:
-
261
retval = super
-
261
if options[:raw] && local_cache && retval
-
4
raw_entry = Entry.new(entry.value.to_s)
-
4
raw_entry.expires_at = entry.expires_at
-
4
local_cache.write_entry(key, raw_entry, options)
-
end
-
261
retval
-
end
-
end
-
end
-
end
-
end
-
1
require 'monitor'
-
-
1
module ActiveSupport
-
1
module Cache
-
# A cache store implementation which stores everything into memory in the
-
# same process. If you're running multiple Ruby on Rails server processes
-
# (which is the case if you're using mongrel_cluster or Phusion Passenger),
-
# then this means that Rails server process instances won't be able
-
# to share cache data with each other and this may not be the most
-
# appropriate cache in that scenario.
-
#
-
# This cache has a bounded size specified by the :size options to the
-
# initializer (default is 32Mb). When the cache exceeds the allotted size,
-
# a cleanup will occur which tries to prune the cache down to three quarters
-
# of the maximum size by removing the least recently used entries.
-
#
-
# MemoryStore is thread-safe.
-
1
class MemoryStore < Store
-
1
def initialize(options = nil)
-
45
options ||= {}
-
45
super(options)
-
45
@data = {}
-
45
@key_access = {}
-
45
@max_size = options[:size] || 32.megabytes
-
45
@max_prune_time = options[:max_prune_time] || 2
-
45
@cache_size = 0
-
45
@monitor = Monitor.new
-
45
@pruning = false
-
end
-
-
1
def clear(options = nil)
-
synchronize do
-
@data.clear
-
@key_access.clear
-
@cache_size = 0
-
end
-
end
-
-
1
def cleanup(options = nil)
-
3
options = merged_options(options)
-
3
instrument(:cleanup, :size => @data.size) do
-
6
keys = synchronize{ @data.keys }
-
3
keys.each do |key|
-
21
entry = @data[key]
-
21
delete_entry(key, options) if entry && entry.expired?
-
end
-
end
-
end
-
-
# To ensure entries fit within the specified memory prune the cache by removing the least
-
# recently accessed entries.
-
1
def prune(target_size, max_time = nil)
-
3
return if pruning?
-
3
@pruning = true
-
3
begin
-
3
start_time = Time.now
-
3
cleanup
-
3
instrument(:prune, target_size, :from => @cache_size) do
-
46
keys = synchronize{ @key_access.keys.sort{|a,b| @key_access[a].to_f <=> @key_access[b].to_f} }
-
3
keys.each do |key|
-
7
delete_entry(key, options)
-
7
return if @cache_size <= target_size || (max_time && Time.now - start_time > max_time)
-
end
-
end
-
ensure
-
3
@pruning = false
-
end
-
end
-
-
# Returns true if the cache is currently being pruned.
-
1
def pruning?
-
3
@pruning
-
end
-
-
# Increment an integer value in the cache.
-
1
def increment(name, amount = 1, options = nil)
-
4
synchronize do
-
4
options = merged_options(options)
-
4
if num = read(name, options)
-
3
num = num.to_i + amount
-
3
write(name, num, options)
-
3
num
-
else
-
1
nil
-
end
-
end
-
end
-
-
# Decrement an integer value in the cache.
-
1
def decrement(name, amount = 1, options = nil)
-
4
synchronize do
-
4
options = merged_options(options)
-
4
if num = read(name, options)
-
3
num = num.to_i - amount
-
3
write(name, num, options)
-
3
num
-
else
-
1
nil
-
end
-
end
-
end
-
-
1
def delete_matched(matcher, options = nil)
-
3
options = merged_options(options)
-
3
instrument(:delete_matched, matcher.inspect) do
-
3
matcher = key_matcher(matcher, options)
-
6
keys = synchronize { @data.keys }
-
3
keys.each do |key|
-
8
delete_entry(key, options) if key.match(matcher)
-
end
-
end
-
end
-
-
1
def inspect # :nodoc:
-
"<##{self.class.name} entries=#{@data.size}, size=#{@cache_size}, options=#{@options.inspect}>"
-
end
-
-
# Synchronize calls to the cache. This should be called wherever the underlying cache implementation
-
# is not thread safe.
-
1
def synchronize(&block) # :nodoc:
-
217
@monitor.synchronize(&block)
-
end
-
-
1
protected
-
1
def read_entry(key, options) # :nodoc:
-
97
entry = @data[key]
-
97
synchronize do
-
97
if entry
-
74
@key_access[key] = Time.now.to_f
-
else
-
23
@key_access.delete(key)
-
end
-
end
-
97
entry
-
end
-
-
1
def write_entry(key, entry, options) # :nodoc:
-
85
entry.dup_value!
-
85
synchronize do
-
85
old_entry = @data[key]
-
85
return false if @data.key?(key) && options[:unless_exist]
-
83
@cache_size -= old_entry.size if old_entry
-
83
@cache_size += entry.size
-
83
@key_access[key] = Time.now.to_f
-
83
@data[key] = entry
-
83
prune(@max_size * 0.75, @max_prune_time) if @cache_size > @max_size
-
83
true
-
end
-
end
-
-
1
def delete_entry(key, options) # :nodoc:
-
18
synchronize do
-
18
@key_access.delete(key)
-
18
entry = @data.delete(key)
-
18
@cache_size -= entry.size if entry
-
18
!!entry
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
1
module Cache
-
# A cache store implementation which doesn't actually store anything. Useful in
-
# development and test environments where you don't want caching turned on but
-
# need to go through the caching interface.
-
#
-
# This cache does implement the local cache strategy, so values will actually
-
# be cached inside blocks that utilize this strategy. See
-
# ActiveSupport::Cache::Strategy::LocalCache for more details.
-
1
class NullStore < Store
-
1
def initialize(options = nil)
-
10
super(options)
-
10
extend Strategy::LocalCache
-
end
-
-
1
def clear(options = nil)
-
end
-
-
1
def cleanup(options = nil)
-
end
-
-
1
def increment(name, amount = 1, options = nil)
-
end
-
-
1
def decrement(name, amount = 1, options = nil)
-
end
-
-
1
def delete_matched(matcher, options = nil)
-
end
-
-
1
protected
-
1
def read_entry(key, options) # :nodoc:
-
end
-
-
1
def write_entry(key, entry, options) # :nodoc:
-
8
true
-
end
-
-
1
def delete_entry(key, options) # :nodoc:
-
2
false
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/duplicable'
-
1
require 'active_support/core_ext/string/inflections'
-
-
1
module ActiveSupport
-
1
module Cache
-
1
module Strategy
-
# Caches that implement LocalCache will be backed by an in-memory cache for the
-
# duration of a block. Repeated calls to the cache for the same key will hit the
-
# in-memory cache for faster access.
-
1
module LocalCache
-
# Simple memory backed cache. This cache is not thread safe and is intended only
-
# for serving as a temporary memory cache for a single thread.
-
1
class LocalStore < Store
-
1
def initialize
-
23
super
-
23
@data = {}
-
end
-
-
# Don't allow synchronizing since it isn't thread safe,
-
1
def synchronize # :nodoc:
-
yield
-
end
-
-
1
def clear(options = nil)
-
2
@data.clear
-
end
-
-
1
def read_entry(key, options)
-
22
@data[key]
-
end
-
-
1
def write_entry(key, value, options)
-
35
@data[key] = value
-
35
true
-
end
-
-
1
def delete_entry(key, options)
-
3
!!@data.delete(key)
-
end
-
end
-
-
# Use a local cache for the duration of block.
-
1
def with_local_cache
-
21
save_val = Thread.current[thread_local_key]
-
21
begin
-
21
Thread.current[thread_local_key] = LocalStore.new
-
21
yield
-
ensure
-
21
Thread.current[thread_local_key] = save_val
-
end
-
end
-
-
#--
-
# This class wraps up local storage for middlewares. Only the middleware method should
-
# construct them.
-
1
class Middleware # :nodoc:
-
1
attr_reader :name, :thread_local_key
-
-
1
def initialize(name, thread_local_key)
-
2
@name = name
-
2
@thread_local_key = thread_local_key
-
2
@app = nil
-
end
-
-
1
def new(app)
-
2
@app = app
-
2
self
-
end
-
-
1
def call(env)
-
2
Thread.current[thread_local_key] = LocalStore.new
-
2
@app.call(env)
-
ensure
-
2
Thread.current[thread_local_key] = nil
-
end
-
end
-
-
# Middleware class can be inserted as a Rack handler to be local cache for the
-
# duration of request.
-
1
def middleware
-
@middleware ||= Middleware.new(
-
"ActiveSupport::Cache::Strategy::LocalCache",
-
2
thread_local_key)
-
end
-
-
1
def clear(options = nil) # :nodoc:
-
157
local_cache.clear(options) if local_cache
-
157
super
-
end
-
-
1
def cleanup(options = nil) # :nodoc:
-
1
local_cache.clear(options) if local_cache
-
1
super
-
end
-
-
1
def increment(name, amount = 1, options = nil) # :nodoc:
-
218
value = bypass_local_cache{super}
-
107
if local_cache
-
1
local_cache.mute do
-
1
if value
-
1
local_cache.write(name, value, options)
-
else
-
local_cache.delete(name, options)
-
end
-
end
-
end
-
107
value
-
end
-
-
1
def decrement(name, amount = 1, options = nil) # :nodoc:
-
214
value = bypass_local_cache{super}
-
105
if local_cache
-
1
local_cache.mute do
-
1
if value
-
1
local_cache.write(name, value, options)
-
else
-
local_cache.delete(name, options)
-
end
-
end
-
end
-
105
value
-
end
-
-
1
protected
-
1
def read_entry(key, options) # :nodoc:
-
431
if local_cache
-
22
entry = local_cache.read_entry(key, options)
-
22
unless entry
-
7
entry = super
-
7
local_cache.write_entry(key, entry, options)
-
end
-
22
entry
-
else
-
409
super
-
end
-
end
-
-
1
def write_entry(key, entry, options) # :nodoc:
-
331
local_cache.write_entry(key, entry, options) if local_cache
-
331
super
-
end
-
-
1
def delete_entry(key, options) # :nodoc:
-
121
local_cache.delete_entry(key, options) if local_cache
-
121
super
-
end
-
-
1
private
-
1
def thread_local_key
-
2348
@thread_local_key ||= "#{self.class.name.underscore}_local_cache_#{object_id}".gsub(/[\/-]/, '_').to_sym
-
end
-
-
1
def local_cache
-
1635
Thread.current[thread_local_key]
-
end
-
-
1
def bypass_local_cache
-
216
save_cache = Thread.current[thread_local_key]
-
216
begin
-
216
Thread.current[thread_local_key] = nil
-
216
yield
-
ensure
-
216
Thread.current[thread_local_key] = save_cache
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/concern'
-
1
require 'active_support/descendants_tracker'
-
1
require 'active_support/core_ext/class/attribute'
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
-
1
module ActiveSupport
-
# Callbacks are code hooks that are run at key points in an object's lifecycle.
-
# The typical use case is to have a base class define a set of callbacks
-
# relevant to the other functionality it supplies, so that subclasses can
-
# install callbacks that enhance or modify the base functionality without
-
# needing to override or redefine methods of the base class.
-
#
-
# Mixing in this module allows you to define the events in the object's
-
# lifecycle that will support callbacks (via +ClassMethods.define_callbacks+),
-
# set the instance methods, procs, or callback objects to be called (via
-
# +ClassMethods.set_callback+), and run the installed callbacks at the
-
# appropriate times (via +run_callbacks+).
-
#
-
# Three kinds of callbacks are supported: before callbacks, run before a
-
# certain event; after callbacks, run after the event; and around callbacks,
-
# blocks that surround the event, triggering it when they yield. Callback code
-
# can be contained in instance methods, procs or lambdas, or callback objects
-
# that respond to certain predetermined methods. See +ClassMethods.set_callback+
-
# for details.
-
#
-
# class Record
-
# include ActiveSupport::Callbacks
-
# define_callbacks :save
-
#
-
# def save
-
# run_callbacks :save do
-
# puts "- save"
-
# end
-
# end
-
# end
-
#
-
# class PersonRecord < Record
-
# set_callback :save, :before, :saving_message
-
# def saving_message
-
# puts "saving..."
-
# end
-
#
-
# set_callback :save, :after do |object|
-
# puts "saved"
-
# end
-
# end
-
#
-
# person = PersonRecord.new
-
# person.save
-
#
-
# Output:
-
# saving...
-
# - save
-
# saved
-
1
module Callbacks
-
1
extend Concern
-
-
1
included do
-
16
extend ActiveSupport::DescendantsTracker
-
end
-
-
# Runs the callbacks for the given event.
-
#
-
# Calls the before and around callbacks in the order they were set, yields
-
# the block (if given one), and then runs the after callbacks in reverse
-
# order.
-
#
-
# If the callback chain was halted, returns +false+. Otherwise returns the
-
# result of the block, or +true+ if no block is given.
-
#
-
# run_callbacks :save do
-
# save
-
# end
-
1
def run_callbacks(kind, &block)
-
5765
runner_name = self.class.__define_callbacks(kind, self)
-
5765
send(runner_name, &block)
-
end
-
-
1
private
-
-
# A hook invoked everytime a before callback is halted.
-
# This can be overridden in AS::Callback implementors in order
-
# to provide better debugging/logging.
-
1
def halted_callback_hook(filter)
-
end
-
-
1
class Callback #:nodoc:#
-
1
@@_callback_sequence = 0
-
-
1
attr_accessor :chain, :filter, :kind, :options, :klass, :raw_filter
-
-
1
def initialize(chain, filter, kind, options, klass)
-
87
@chain, @kind, @klass = chain, kind, klass
-
87
deprecate_per_key_option(options)
-
86
normalize_options!(options)
-
-
86
@raw_filter, @options = filter, options
-
86
@filter = _compile_filter(filter)
-
86
recompile_options!
-
end
-
-
1
def deprecate_per_key_option(options)
-
95
if options[:per_key]
-
2
raise NotImplementedError, ":per_key option is no longer supported. Use generic :if and :unless options instead."
-
end
-
end
-
-
1
def clone(chain, klass)
-
8
obj = super()
-
8
obj.chain = chain
-
8
obj.klass = klass
-
8
obj.options = @options.dup
-
8
obj.options[:if] = @options[:if].dup
-
8
obj.options[:unless] = @options[:unless].dup
-
8
obj
-
end
-
-
1
def normalize_options!(options)
-
86
options[:if] = Array(options[:if])
-
86
options[:unless] = Array(options[:unless])
-
end
-
-
1
def name
-
1
chain.name
-
end
-
-
1
def next_id
-
183
@@_callback_sequence += 1
-
end
-
-
1
def matches?(_kind, _filter)
-
278
@kind == _kind && @filter == _filter
-
end
-
-
1
def _update_filter(filter_options, new_options)
-
7
filter_options[:if].concat(Array(new_options[:unless])) if new_options.key?(:unless)
-
7
filter_options[:unless].concat(Array(new_options[:if])) if new_options.key?(:if)
-
end
-
-
1
def recompile!(_options)
-
8
deprecate_per_key_option(_options)
-
7
_update_filter(self.options, _options)
-
-
7
recompile_options!
-
end
-
-
# Wraps code with filter
-
1
def apply(code)
-
110
case @kind
-
when :before
-
<<-RUBY_EVAL
-
65
if !halted && #{@compiled_options}
-
# This double assignment is to prevent warnings in 1.9.3 as
-
# the `result` variable is not always used except if the
-
# terminator code refers to it.
-
result = result = #{@filter}
-
halted = (#{chain.config[:terminator]})
-
if halted
-
halted_callback_hook(#{@raw_filter.inspect.inspect})
-
end
-
end
-
#{code}
-
RUBY_EVAL
-
when :after
-
<<-RUBY_EVAL
-
38
#{code}
-
if #{!chain.config[:skip_after_callbacks_if_terminated] || "!halted"} && #{@compiled_options}
-
#{@filter}
-
end
-
RUBY_EVAL
-
when :around
-
7
name = define_conditional_callback
-
<<-RUBY_EVAL
-
7
#{name}(halted) do
-
#{code}
-
value
-
end
-
RUBY_EVAL
-
end
-
end
-
-
1
private
-
-
# Compile around filters with conditions into proxy methods
-
# that contain the conditions.
-
#
-
# For `set_callback :save, :around, :filter_name, if: :condition':
-
#
-
# def _conditional_callback_save_17
-
# if condition
-
# filter_name do
-
# yield self
-
# end
-
# else
-
# yield self
-
# end
-
# end
-
1
def define_conditional_callback
-
7
name = "_conditional_callback_#{@kind}_#{next_id}"
-
7
@klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def #{name}(halted)
-
if #{@compiled_options} && !halted
-
#{@filter} do
-
yield self
-
end
-
else
-
yield self
-
end
-
end
-
RUBY_EVAL
-
7
name
-
end
-
-
# Options support the same options as filters themselves (and support
-
# symbols, string, procs, and objects), so compile a conditional
-
# expression based on the options.
-
1
def recompile_options!
-
93
conditions = ["true"]
-
-
93
unless options[:if].empty?
-
24
conditions << Array(_compile_filter(options[:if]))
-
end
-
-
93
unless options[:unless].empty?
-
39
conditions << Array(_compile_filter(options[:unless])).map {|f| "!#{f}"}
-
end
-
-
93
@compiled_options = conditions.flatten.join(" && ")
-
end
-
-
# Filters support:
-
#
-
# Arrays:: Used in conditions. This is used to specify
-
# multiple conditions. Used internally to
-
# merge conditions from skip_* filters.
-
# Symbols:: A method to call.
-
# Strings:: Some content to evaluate.
-
# Procs:: A proc to call with the object.
-
# Objects:: An object with a <tt>before_foo</tt> method on it to call.
-
#
-
# All of these objects are compiled into methods and handled
-
# the same after this point:
-
#
-
# Arrays:: Merged together into a single filter.
-
# Symbols:: Already methods.
-
# Strings:: class_eval'ed into methods.
-
# Procs:: define_method'ed into methods.
-
# Objects::
-
# a method is created that calls the before_foo method
-
# on the object.
-
1
def _compile_filter(filter)
-
176
method_name = "_callback_#{@kind}_#{next_id}"
-
176
case filter
-
when Array
-
90
filter.map {|f| _compile_filter(f)}
-
when Symbol
-
71
filter
-
when String
-
7
"(#{filter})"
-
when Proc
-
50
@klass.send(:define_method, method_name, &filter)
-
50
return method_name if filter.arity <= 0
-
-
42
method_name << (filter.arity == 1 ? "(self)" : " self, Proc.new ")
-
else
-
15
@klass.send(:define_method, "#{method_name}_object") { filter }
-
-
5
_normalize_legacy_filter(kind, filter)
-
5
scopes = Array(chain.config[:scope])
-
11
method_to_call = scopes.map{ |s| s.is_a?(Symbol) ? send(s) : s }.join("_")
-
-
5
@klass.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def #{method_name}(&blk)
-
#{method_name}_object.send(:#{method_to_call}, self, &blk)
-
end
-
RUBY_EVAL
-
-
5
method_name
-
end
-
end
-
-
1
def _normalize_legacy_filter(kind, filter)
-
5
if !filter.respond_to?(kind) && filter.respond_to?(:filter)
-
message = "Filter object with #filter method is deprecated. Define method corresponding " \
-
"to filter type (#before, #after or #around)."
-
ActiveSupport::Deprecation.warn message
-
filter.singleton_class.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def #{kind}(context, &block) filter(context, &block) end
-
RUBY_EVAL
-
5
elsif filter.respond_to?(:before) && filter.respond_to?(:after) && kind == :around && !filter.respond_to?(:around)
-
message = "Filter object with #before and #after methods is deprecated. Define #around method instead."
-
ActiveSupport::Deprecation.warn message
-
def filter.around(context)
-
should_continue = before(context)
-
yield if should_continue
-
after(context)
-
end
-
end
-
end
-
end
-
-
# An Array with a compile method.
-
1
class CallbackChain < Array #:nodoc:#
-
1
attr_reader :name, :config
-
-
1
def initialize(name, config)
-
28
@name = name
-
28
@config = {
-
:terminator => "false",
-
:scope => [ :kind ]
-
}.merge(config)
-
end
-
-
1
def compile
-
353
method = []
-
353
method << "value = nil"
-
353
method << "halted = false"
-
-
353
callbacks = "value = !halted && (!block_given? || yield)"
-
353
reverse_each do |callback|
-
110
callbacks = callback.apply(callbacks)
-
end
-
353
method << callbacks
-
-
353
method << "value"
-
353
method.join("\n")
-
end
-
-
end
-
-
1
module ClassMethods
-
-
# This method defines callback chain method for the given kind
-
# if it was not yet defined.
-
# This generated method plays caching role.
-
1
def __define_callbacks(kind, object) #:nodoc:
-
5765
name = __callback_runner_name(kind)
-
5765
unless object.respond_to?(name, true)
-
353
str = object.send("_#{kind}_callbacks").compile
-
353
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def #{name}() #{str} end
-
protected :#{name}
-
RUBY_EVAL
-
end
-
5765
name
-
end
-
-
1
def __reset_runner(symbol)
-
95
name = __callback_runner_name(symbol)
-
95
undef_method(name) if method_defined?(name)
-
end
-
-
1
def __callback_runner_name(kind)
-
5860
"_run__#{self.name.hash.abs}__#{kind}__callbacks"
-
end
-
-
# This is used internally to append, prepend and skip callbacks to the
-
# CallbackChain.
-
1
def __update_callbacks(name, filters = [], block = nil) #:nodoc:
-
94
type = [:before, :after, :around].include?(filters.first) ? filters.shift : :before
-
94
options = filters.last.is_a?(Hash) ? filters.pop : {}
-
94
filters.unshift(block) if block
-
-
94
([self] + ActiveSupport::DescendantsTracker.descendants(self)).reverse.each do |target|
-
96
chain = target.send("_#{name}_callbacks")
-
96
yield target, chain.dup, type, filters, options
-
94
target.__reset_runner(name)
-
end
-
end
-
-
# Install a callback for the given event.
-
#
-
# set_callback :save, :before, :before_meth
-
# set_callback :save, :after, :after_meth, if: :condition
-
# set_callback :save, :around, ->(r, &block) { stuff; result = block.call; stuff }
-
#
-
# The second arguments indicates whether the callback is to be run +:before+,
-
# +:after+, or +:around+ the event. If omitted, +:before+ is assumed. This
-
# means the first example above can also be written as:
-
#
-
# set_callback :save, :before_meth
-
#
-
# The callback can specified as a symbol naming an instance method; as a
-
# proc, lambda, or block; as a string to be instance evaluated; or as an
-
# object that responds to a certain method determined by the <tt>:scope</tt>
-
# argument to +define_callback+.
-
#
-
# If a proc, lambda, or block is given, its body is evaluated in the context
-
# of the current object. It can also optionally accept the current object as
-
# an argument.
-
#
-
# Before and around callbacks are called in the order that they are set;
-
# after callbacks are called in the reverse order.
-
#
-
# Around callbacks can access the return value from the event, if it
-
# wasn't halted, from the +yield+ call.
-
#
-
# ===== Options
-
#
-
# * <tt>:if</tt> - A symbol naming an instance method or a proc; the
-
# callback will be called only when it returns a +true+ value.
-
# * <tt>:unless</tt> - A symbol naming an instance method or a proc; the
-
# callback will be called only when it returns a +false+ value.
-
# * <tt>:prepend</tt> - If +true+, the callback will be prepended to the
-
# existing chain rather than appended.
-
1
def set_callback(name, *filter_list, &block)
-
83
mapped = nil
-
-
83
__update_callbacks(name, filter_list, block) do |target, chain, type, filters, options|
-
mapped ||= filters.map do |filter|
-
87
Callback.new(chain, filter, type, options.dup, self)
-
85
end
-
-
84
filters.each do |filter|
-
331
chain.delete_if {|c| c.matches?(type, filter) }
-
end
-
-
84
options[:prepend] ? chain.unshift(*(mapped.reverse)) : chain.push(*mapped)
-
-
84
target.send("_#{name}_callbacks=", chain)
-
end
-
end
-
-
# Skip a previously set callback. Like +set_callback+, <tt>:if</tt> or
-
# <tt>:unless</tt> options may be passed in order to control when the
-
# callback is skipped.
-
#
-
# class Writer < Person
-
# skip_callback :validate, :before, :check_membership, if: -> { self.age > 18 }
-
# end
-
1
def skip_callback(name, *filter_list, &block)
-
11
__update_callbacks(name, filter_list, block) do |target, chain, type, filters, options|
-
11
filters.each do |filter|
-
46
filter = chain.find {|c| c.matches?(type, filter) }
-
-
11
if filter && options.any?
-
8
new_filter = filter.clone(chain, self)
-
8
chain.insert(chain.index(filter), new_filter)
-
8
new_filter.recompile!(options)
-
end
-
-
10
chain.delete(filter)
-
end
-
10
target.send("_#{name}_callbacks=", chain)
-
end
-
end
-
-
# Remove all set callbacks for the given event.
-
1
def reset_callbacks(symbol)
-
1
callbacks = send("_#{symbol}_callbacks")
-
-
1
ActiveSupport::DescendantsTracker.descendants(self).each do |target|
-
chain = target.send("_#{symbol}_callbacks").dup
-
callbacks.each { |c| chain.delete(c) }
-
target.send("_#{symbol}_callbacks=", chain)
-
target.__reset_runner(symbol)
-
end
-
-
1
self.send("_#{symbol}_callbacks=", callbacks.dup.clear)
-
-
1
__reset_runner(symbol)
-
end
-
-
# Define sets of events in the object lifecycle that support callbacks.
-
#
-
# define_callbacks :validate
-
# define_callbacks :initialize, :save, :destroy
-
#
-
# ===== Options
-
#
-
# * <tt>:terminator</tt> - Determines when a before filter will halt the
-
# callback chain, preventing following callbacks from being called and
-
# the event from being triggered. This is a string to be eval'ed. The
-
# result of the callback is available in the +result+ variable.
-
#
-
# define_callbacks :validate, terminator: 'result == false'
-
#
-
# In this example, if any before validate callbacks returns +false+,
-
# other callbacks are not executed. Defaults to +false+, meaning no value
-
# halts the chain.
-
#
-
# * <tt>:skip_after_callbacks_if_terminated</tt> - Determines if after
-
# callbacks should be terminated by the <tt>:terminator</tt> option. By
-
# default after callbacks executed no matter if callback chain was
-
# terminated or not. Option makes sense only when <tt>:terminator</tt>
-
# option is specified.
-
#
-
# * <tt>:scope</tt> - Indicates which methods should be executed when an
-
# object is used as a callback.
-
#
-
# class Audit
-
# def before(caller)
-
# puts 'Audit: before is called'
-
# end
-
#
-
# def before_save(caller)
-
# puts 'Audit: before_save is called'
-
# end
-
# end
-
#
-
# class Account
-
# include ActiveSupport::Callbacks
-
#
-
# define_callbacks :save
-
# set_callback :save, :before, Audit.new
-
#
-
# def save
-
# run_callbacks :save do
-
# puts 'save in main'
-
# end
-
# end
-
# end
-
#
-
# In the above case whenever you save an account the method
-
# <tt>Audit#before</tt> will be called. On the other hand
-
#
-
# define_callbacks :save, scope: [:kind, :name]
-
#
-
# would trigger <tt>Audit#before_save</tt> instead. That's constructed
-
# by calling <tt>#{kind}_#{name}</tt> on the given instance. In this
-
# case "kind" is "before" and "name" is "save". In this context +:kind+
-
# and +:name+ have special meanings: +:kind+ refers to the kind of
-
# callback (before/after/around) and +:name+ refers to the method on
-
# which callbacks are being defined.
-
#
-
# A declaration like
-
#
-
# define_callbacks :save, scope: [:name]
-
#
-
# would call <tt>Audit#save</tt>.
-
1
def define_callbacks(*callbacks)
-
25
config = callbacks.last.is_a?(Hash) ? callbacks.pop : {}
-
25
callbacks.each do |callback|
-
28
class_attribute "_#{callback}_callbacks"
-
28
send("_#{callback}_callbacks=", CallbackChain.new(callback, config))
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
# A typical module looks like this:
-
#
-
# module M
-
# def self.included(base)
-
# base.extend ClassMethods
-
# scope :disabled, -> { where(disabled: true) }
-
# end
-
#
-
# module ClassMethods
-
# ...
-
# end
-
# end
-
#
-
# By using <tt>ActiveSupport::Concern</tt> the above module could instead be
-
# written as:
-
#
-
# require 'active_support/concern'
-
#
-
# module M
-
# extend ActiveSupport::Concern
-
#
-
# included do
-
# scope :disabled, -> { where(disabled: true) }
-
# end
-
#
-
# module ClassMethods
-
# ...
-
# end
-
# end
-
#
-
# Moreover, it gracefully handles module dependencies. Given a +Foo+ module
-
# and a +Bar+ module which depends on the former, we would typically write the
-
# following:
-
#
-
# module Foo
-
# def self.included(base)
-
# base.class_eval do
-
# def self.method_injected_by_foo
-
# ...
-
# end
-
# end
-
# end
-
# end
-
#
-
# module Bar
-
# def self.included(base)
-
# base.method_injected_by_foo
-
# end
-
# end
-
#
-
# class Host
-
# include Foo # We need to include this dependency for Bar
-
# include Bar # Bar is the module that Host really needs
-
# end
-
#
-
# But why should +Host+ care about +Bar+'s dependencies, namely +Foo+? We
-
# could try to hide these from +Host+ directly including +Foo+ in +Bar+:
-
#
-
# module Bar
-
# include Foo
-
# def self.included(base)
-
# base.method_injected_by_foo
-
# end
-
# end
-
#
-
# class Host
-
# include Bar
-
# end
-
#
-
# Unfortunately this won't work, since when +Foo+ is included, its <tt>base</tt>
-
# is the +Bar+ module, not the +Host+ class. With <tt>ActiveSupport::Concern</tt>,
-
# module dependencies are properly resolved:
-
#
-
# require 'active_support/concern'
-
#
-
# module Foo
-
# extend ActiveSupport::Concern
-
# included do
-
# class_eval do
-
# def self.method_injected_by_foo
-
# ...
-
# end
-
# end
-
# end
-
# end
-
#
-
# module Bar
-
# extend ActiveSupport::Concern
-
# include Foo
-
#
-
# included do
-
# self.method_injected_by_foo
-
# end
-
# end
-
#
-
# class Host
-
# include Bar # works, Bar takes care now of its dependencies
-
# end
-
1
module Concern
-
1
def self.extended(base) #:nodoc:
-
53
base.instance_variable_set("@_dependencies", [])
-
end
-
-
1
def append_features(base)
-
91
if base.instance_variable_defined?("@_dependencies")
-
10
base.instance_variable_get("@_dependencies") << self
-
10
return false
-
else
-
81
return false if base < self
-
87
@_dependencies.each { |dep| base.send(:include, dep) }
-
76
super
-
76
base.extend const_get("ClassMethods") if const_defined?("ClassMethods")
-
76
base.class_eval(&@_included_block) if instance_variable_defined?("@_included_block")
-
end
-
end
-
-
1
def included(base = nil, &block)
-
126
if base.nil?
-
35
@_included_block = block
-
else
-
91
super
-
end
-
end
-
end
-
end
-
1
require 'active_support/concern'
-
1
require 'active_support/ordered_options'
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
module ActiveSupport
-
# Configurable provides a <tt>config</tt> method to store and retrieve
-
# configuration options as an <tt>OrderedHash</tt>.
-
1
module Configurable
-
1
extend ActiveSupport::Concern
-
-
1
class Configuration < ActiveSupport::InheritableOptions
-
1
def compile_methods!
-
1
self.class.compile_methods!(keys)
-
end
-
-
# Compiles reader methods so we don't have to go through method_missing.
-
1
def self.compile_methods!(keys)
-
2
keys.reject { |m| method_defined?(m) }.each do |key|
-
1
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def #{key}; _get(#{key.inspect}); end
-
RUBY
-
end
-
end
-
end
-
-
1
module ClassMethods
-
1
def config
-
@_config ||= if respond_to?(:superclass) && superclass.respond_to?(:config)
-
2
superclass.config.inheritable_copy
-
else
-
# create a new "anonymous" class that will host the compiled reader methods
-
4
Class.new(Configuration).new
-
51
end
-
end
-
-
1
def configure
-
yield config
-
end
-
-
# Allows you to add shortcut so that you don't have to refer to attribute
-
# through config. Also look at the example for config to contrast.
-
#
-
# Defines both class and instance config accessors.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :allowed_access
-
# end
-
#
-
# User.allowed_access # => nil
-
# User.allowed_access = false
-
# User.allowed_access # => false
-
#
-
# user = User.new
-
# user.allowed_access # => false
-
# user.allowed_access = true
-
# user.allowed_access # => true
-
#
-
# User.allowed_access # => false
-
#
-
# The attribute name must be a valid method name in Ruby.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :"1_Badname"
-
# end
-
# # => NameError: invalid config attribute name
-
#
-
# To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
-
# To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :allowed_access, instance_reader: false, instance_writer: false
-
# end
-
#
-
# User.allowed_access = false
-
# User.allowed_access # => false
-
#
-
# User.new.allowed_access = true # => NoMethodError
-
# User.new.allowed_access # => NoMethodError
-
#
-
# Or pass <tt>instance_accessor: false</tt>, to opt out both instance methods.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :allowed_access, instance_accessor: false
-
# end
-
#
-
# User.allowed_access = false
-
# User.allowed_access # => false
-
#
-
# User.new.allowed_access = true # => NoMethodError
-
# User.new.allowed_access # => NoMethodError
-
#
-
# Also you can pass a block to set up the attribute with a default value.
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# config_accessor :hair_colors do
-
# [:brown, :black, :blonde, :red]
-
# end
-
# end
-
#
-
# User.hair_colors # => [:brown, :black, :blonde, :red]
-
1
def config_accessor(*names)
-
5
options = names.extract_options!
-
-
5
names.each do |name|
-
6
raise NameError.new('invalid config attribute name') unless name =~ /^[_A-Za-z]\w*$/
-
-
5
reader, reader_line = "def #{name}; config.#{name}; end", __LINE__
-
5
writer, writer_line = "def #{name}=(value); config.#{name} = value; end", __LINE__
-
-
5
singleton_class.class_eval reader, __FILE__, reader_line
-
5
singleton_class.class_eval writer, __FILE__, writer_line
-
-
5
unless options[:instance_accessor] == false
-
4
class_eval reader, __FILE__, reader_line unless options[:instance_reader] == false
-
4
class_eval writer, __FILE__, writer_line unless options[:instance_writer] == false
-
end
-
5
send("#{name}=", yield) if block_given?
-
end
-
end
-
end
-
-
# Reads and writes attributes from a configuration <tt>OrderedHash</tt>.
-
#
-
# require 'active_support/configurable'
-
#
-
# class User
-
# include ActiveSupport::Configurable
-
# end
-
#
-
# user = User.new
-
#
-
# user.config.allowed_access = true
-
# user.config.level = 1
-
#
-
# user.config.allowed_access # => true
-
# user.config.level # => 1
-
1
def config
-
6
@_config ||= self.class.config.inheritable_copy
-
end
-
end
-
end
-
-
1
Dir["#{File.dirname(__FILE__)}/core_ext/*.rb"].sort.each do |path|
-
24
next if File.basename(path, '.rb') == 'logger'
-
23
require "active_support/core_ext/#{File.basename(path, '.rb')}"
-
end
-
1
require 'active_support/core_ext/array/wrap'
-
1
require 'active_support/core_ext/array/access'
-
1
require 'active_support/core_ext/array/uniq_by'
-
1
require 'active_support/core_ext/array/conversions'
-
1
require 'active_support/core_ext/array/extract_options'
-
1
require 'active_support/core_ext/array/grouping'
-
1
require 'active_support/core_ext/array/prepend_and_append'
-
1
class Array
-
# Returns the tail of the array from +position+.
-
#
-
# %w( a b c d ).from(0) # => ["a", "b", "c", "d"]
-
# %w( a b c d ).from(2) # => ["c", "d"]
-
# %w( a b c d ).from(10) # => []
-
# %w().from(0) # => []
-
1
def from(position)
-
3
self[position, length] || []
-
end
-
-
# Returns the beginning of the array up to +position+.
-
#
-
# %w( a b c d ).to(0) # => ["a"]
-
# %w( a b c d ).to(2) # => ["a", "b", "c"]
-
# %w( a b c d ).to(10) # => ["a", "b", "c", "d"]
-
# %w().to(0) # => []
-
1
def to(position)
-
3
first position + 1
-
end
-
-
# Equal to <tt>self[1]</tt>.
-
#
-
# %w( a b c d e).second # => "b"
-
1
def second
-
1
self[1]
-
end
-
-
# Equal to <tt>self[2]</tt>.
-
#
-
# %w( a b c d e).third # => "c"
-
1
def third
-
1
self[2]
-
end
-
-
# Equal to <tt>self[3]</tt>.
-
#
-
# %w( a b c d e).fourth # => "d"
-
1
def fourth
-
1
self[3]
-
end
-
-
# Equal to <tt>self[4]</tt>.
-
#
-
# %w( a b c d e).fifth # => "e"
-
1
def fifth
-
1
self[4]
-
end
-
-
# Equal to <tt>self[41]</tt>. Also known as accessing "the reddit".
-
1
def forty_two
-
1
self[41]
-
end
-
end
-
1
require 'active_support/xml_mini'
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/core_ext/object/to_param'
-
1
require 'active_support/core_ext/object/to_query'
-
-
1
class Array
-
# Converts the array to a comma-separated sentence where the last element is
-
# joined by the connector word.
-
#
-
# You can pass the following options to change the default behaviour. If you
-
# pass an option key that doesn't exist in the list below, it will raise an
-
# <tt>ArgumentError</tt>.
-
#
-
# Options:
-
#
-
# * <tt>:words_connector</tt> - The sign or word used to join the elements
-
# in arrays with two or more elements (default: ", ").
-
# * <tt>:two_words_connector</tt> - The sign or word used to join the elements
-
# in arrays with two elements (default: " and ").
-
# * <tt>:last_word_connector</tt> - The sign or word used to join the last element
-
# in arrays with three or more elements (default: ", and ").
-
# * <tt>:locale</tt> - If +i18n+ is available, you can set a locale and use
-
# the connector options defined on the 'support.array' namespace in the
-
# corresponding dictionary file.
-
#
-
# [].to_sentence # => ""
-
# ['one'].to_sentence # => "one"
-
# ['one', 'two'].to_sentence # => "one and two"
-
# ['one', 'two', 'three'].to_sentence # => "one, two, and three"
-
#
-
# ['one', 'two'].to_sentence(passing: 'invalid option')
-
# # => ArgumentError: Unknown key :passing
-
#
-
# ['one', 'two'].to_sentence(two_words_connector: '-')
-
# # => "one-two"
-
#
-
# ['one', 'two', 'three'].to_sentence(words_connector: ' or ', last_word_connector: ' or at least ')
-
# # => "one or two or at least three"
-
#
-
# Examples using <tt>:locale</tt> option:
-
#
-
# # Given this locale dictionary:
-
# #
-
# # es:
-
# # support:
-
# # array:
-
# # words_connector: " o "
-
# # two_words_connector: " y "
-
# # last_word_connector: " o al menos "
-
#
-
# ['uno', 'dos'].to_sentence(locale: :es)
-
# # => "uno y dos"
-
#
-
# ['uno', 'dos', 'tres'].to_sentence(locale: :es)
-
# # => "uno o dos o al menos tres"
-
1
def to_sentence(options = {})
-
29
options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale)
-
-
29
default_connectors = {
-
:words_connector => ', ',
-
:two_words_connector => ' and ',
-
:last_word_connector => ', and '
-
}
-
29
if defined?(I18n)
-
29
i18n_connectors = I18n.translate(:'support.array', locale: options[:locale], default: {})
-
29
default_connectors.merge!(i18n_connectors)
-
end
-
29
options = default_connectors.merge!(options)
-
-
29
case length
-
when 0
-
1
''
-
when 1
-
9
self[0].to_s.dup
-
when 2
-
6
"#{self[0]}#{options[:two_words_connector]}#{self[1]}"
-
else
-
13
"#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}"
-
end
-
end
-
-
# Converts a collection of elements into a formatted string by calling
-
# <tt>to_s</tt> on all elements and joining them. Having this model:
-
#
-
# class Blog < ActiveRecord::Base
-
# def to_s
-
# title
-
# end
-
# end
-
#
-
# Blog.all.map(&:title) #=> ["First Post", "Second Post", "Third post"]
-
#
-
# <tt>to_formatted_s</tt> shows us:
-
#
-
# Blog.all.to_formatted_s # => "First PostSecond PostThird Post"
-
#
-
# Adding in the <tt>:db</tt> argument as the format yields a comma separated
-
# id list:
-
#
-
# Blog.all.to_formatted_s(:db) # => "1,2,3"
-
1
def to_formatted_s(format = :default)
-
27
case format
-
when :db
-
2
if empty?
-
1
'null'
-
else
-
4
collect { |element| element.id }.join(',')
-
end
-
else
-
25
to_default_s
-
end
-
end
-
1
alias_method :to_default_s, :to_s
-
1
alias_method :to_s, :to_formatted_s
-
-
# Returns a string that represents the array in XML by invoking +to_xml+
-
# on each element. Active Record collections delegate their representation
-
# in XML to this method.
-
#
-
# All elements are expected to respond to +to_xml+, if any of them does
-
# not then an exception is raised.
-
#
-
# The root node reflects the class name of the first element in plural
-
# if all elements belong to the same type and that's not Hash:
-
#
-
# customer.projects.to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <projects type="array">
-
# <project>
-
# <amount type="decimal">20000.0</amount>
-
# <customer-id type="integer">1567</customer-id>
-
# <deal-date type="date">2008-04-09</deal-date>
-
# ...
-
# </project>
-
# <project>
-
# <amount type="decimal">57230.0</amount>
-
# <customer-id type="integer">1567</customer-id>
-
# <deal-date type="date">2008-04-15</deal-date>
-
# ...
-
# </project>
-
# </projects>
-
#
-
# Otherwise the root element is "objects":
-
#
-
# [{ foo: 1, bar: 2}, { baz: 3}].to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <objects type="array">
-
# <object>
-
# <bar type="integer">2</bar>
-
# <foo type="integer">1</foo>
-
# </object>
-
# <object>
-
# <baz type="integer">3</baz>
-
# </object>
-
# </objects>
-
#
-
# If the collection is empty the root element is "nil-classes" by default:
-
#
-
# [].to_xml
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <nil-classes type="array"/>
-
#
-
# To ensure a meaningful root element use the <tt>:root</tt> option:
-
#
-
# customer_with_no_projects.projects.to_xml(root: 'projects')
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <projects type="array"/>
-
#
-
# By default name of the node for the children of root is <tt>root.singularize</tt>.
-
# You can change it with the <tt>:children</tt> option.
-
#
-
# The +options+ hash is passed downwards:
-
#
-
# Message.all.to_xml(skip_types: true)
-
#
-
# <?xml version="1.0" encoding="UTF-8"?>
-
# <messages>
-
# <message>
-
# <created-at>2008-03-07T09:58:18+01:00</created-at>
-
# <id>1</id>
-
# <name>1</name>
-
# <updated-at>2008-03-07T09:58:18+01:00</updated-at>
-
# <user-id>1</user-id>
-
# </message>
-
# </messages>
-
#
-
1
def to_xml(options = {})
-
12
require 'active_support/builder' unless defined?(Builder)
-
-
12
options = options.dup
-
12
options[:indent] ||= 2
-
12
options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent])
-
12
options[:root] ||= \
-
if first.class != Hash && all? { |e| e.is_a?(first.class) }
-
2
underscored = ActiveSupport::Inflector.underscore(first.class.name)
-
2
ActiveSupport::Inflector.pluralize(underscored).tr('/', '_')
-
else
-
6
'objects'
-
end
-
-
12
builder = options[:builder]
-
12
builder.instruct! unless options.delete(:skip_instruct)
-
-
12
root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options)
-
12
children = options.delete(:children) || root.singularize
-
12
attributes = options[:skip_types] ? {} : { type: 'array' }
-
-
12
if empty?
-
2
builder.tag!(root, attributes)
-
else
-
10
builder.tag!(root, attributes) do
-
29
each { |value| ActiveSupport::XmlMini.to_tag(children, value, options) }
-
10
yield builder if block_given?
-
end
-
end
-
end
-
end
-
1
class Hash
-
# By default, only instances of Hash itself are extractable.
-
# Subclasses of Hash may implement this method and return
-
# true to declare themselves as extractable. If a Hash
-
# is extractable, Array#extract_options! pops it from
-
# the Array when it is the last element of the Array.
-
1
def extractable_options?
-
569
instance_of?(Hash)
-
end
-
end
-
-
1
class Array
-
# Extracts options from a set of arguments. Removes and returns the last
-
# element in the array if it's a hash, otherwise returns a blank hash.
-
#
-
# def options(*args)
-
# args.extract_options!
-
# end
-
#
-
# options(1, 2) # => {}
-
# options(1, 2, a: :b) # => {:a=>:b}
-
1
def extract_options!
-
846
if last.is_a?(Hash) && last.extractable_options?
-
571
pop
-
else
-
275
{}
-
end
-
end
-
end
-
1
class Array
-
# Splits or iterates over the array in groups of size +number+,
-
# padding any remaining slots with +fill_with+ unless it is +false+.
-
#
-
# %w(1 2 3 4 5 6 7 8 9 10).in_groups_of(3) {|group| p group}
-
# ["1", "2", "3"]
-
# ["4", "5", "6"]
-
# ["7", "8", "9"]
-
# ["10", nil, nil]
-
#
-
# %w(1 2 3 4 5).in_groups_of(2, ' ') {|group| p group}
-
# ["1", "2"]
-
# ["3", "4"]
-
# ["5", " "]
-
#
-
# %w(1 2 3 4 5).in_groups_of(2, false) {|group| p group}
-
# ["1", "2"]
-
# ["3", "4"]
-
# ["5"]
-
1
def in_groups_of(number, fill_with = nil)
-
5
if fill_with == false
-
1
collection = self
-
else
-
# size % number gives how many extra we have;
-
# subtracting from number gives how many to add;
-
# modulo number ensures we don't add group of just fill.
-
4
padding = (number - size % number) % number
-
4
collection = dup.concat([fill_with] * padding)
-
end
-
-
5
if block_given?
-
16
collection.each_slice(number) { |slice| yield(slice) }
-
else
-
1
groups = []
-
4
collection.each_slice(number) { |group| groups << group }
-
1
groups
-
end
-
end
-
-
# Splits or iterates over the array in +number+ of groups, padding any
-
# remaining slots with +fill_with+ unless it is +false+.
-
#
-
# %w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group}
-
# ["1", "2", "3", "4"]
-
# ["5", "6", "7", nil]
-
# ["8", "9", "10", nil]
-
#
-
# %w(1 2 3 4 5 6 7 8 9 10).in_groups(3, ' ') {|group| p group}
-
# ["1", "2", "3", "4"]
-
# ["5", "6", "7", " "]
-
# ["8", "9", "10", " "]
-
#
-
# %w(1 2 3 4 5 6 7).in_groups(3, false) {|group| p group}
-
# ["1", "2", "3"]
-
# ["4", "5"]
-
# ["6", "7"]
-
1
def in_groups(number, fill_with = nil)
-
# size / number gives minor group size;
-
# size % number gives how many objects need extra accommodation;
-
# each group hold either division or division + 1 items.
-
15
division = size / number
-
15
modulo = size % number
-
-
# create a new array avoiding dup
-
15
groups = []
-
15
start = 0
-
-
15
number.times do |index|
-
57
length = division + (modulo > 0 && modulo > index ? 1 : 0)
-
57
padding = fill_with != false &&
-
modulo > 0 && length == division ? 1 : 0
-
57
groups << slice(start, length).concat([fill_with] * padding)
-
57
start += length
-
end
-
-
15
if block_given?
-
4
groups.each { |g| yield(g) }
-
else
-
14
groups
-
end
-
end
-
-
# Divides the array into one or more subarrays based on a delimiting +value+
-
# or the result of an optional block.
-
#
-
# [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]]
-
# (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]]
-
1
def split(value = nil, &block)
-
7
inject([[]]) do |results, element|
-
35
if block && block.call(element) || value == element
-
8
results << []
-
else
-
27
results.last << element
-
end
-
-
35
results
-
end
-
end
-
end
-
1
class Array
-
# The human way of thinking about adding stuff to the end of a list is with append
-
1
alias_method :append, :<<
-
-
# The human way of thinking about adding stuff to the beginning of a list is with prepend
-
1
alias_method :prepend, :unshift
-
end
-
1
class Array
-
# *DEPRECATED*: Use +Array#uniq+ instead.
-
#
-
# Returns a unique array based on the criteria in the block.
-
#
-
# [1, 2, 3, 4].uniq_by { |i| i.odd? } # => [1, 2]
-
1
def uniq_by(&block)
-
3
ActiveSupport::Deprecation.warn 'uniq_by is deprecated. Use Array#uniq instead'
-
3
uniq(&block)
-
end
-
-
# *DEPRECATED*: Use +Array#uniq!+ instead.
-
#
-
# Same as +uniq_by+, but modifies +self+.
-
1
def uniq_by!(&block)
-
3
ActiveSupport::Deprecation.warn 'uniq_by! is deprecated. Use Array#uniq! instead'
-
3
uniq!(&block)
-
end
-
end
-
1
class Array
-
# Wraps its argument in an array unless it is already an array (or array-like).
-
#
-
# Specifically:
-
#
-
# * If the argument is +nil+ an empty list is returned.
-
# * Otherwise, if the argument responds to +to_ary+ it is invoked, and its result returned.
-
# * Otherwise, returns an array with the argument as its single element.
-
#
-
# Array.wrap(nil) # => []
-
# Array.wrap([1, 2, 3]) # => [1, 2, 3]
-
# Array.wrap(0) # => [0]
-
#
-
# This method is similar in purpose to <tt>Kernel#Array</tt>, but there are some differences:
-
#
-
# * If the argument responds to +to_ary+ the method is invoked. <tt>Kernel#Array</tt>
-
# moves on to try +to_a+ if the returned value is +nil+, but <tt>Array.wrap</tt> returns
-
# such a +nil+ right away.
-
# * If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, <tt>Kernel#Array</tt>
-
# raises an exception, while <tt>Array.wrap</tt> does not, it just returns the value.
-
# * It does not call +to_a+ on the argument, though special-cases +nil+ to return an empty array.
-
#
-
# The last point is particularly worth comparing for some enumerables:
-
#
-
# Array(foo: :bar) # => [[:foo, :bar]]
-
# Array.wrap(foo: :bar) # => [{:foo=>:bar}]
-
#
-
# There's also a related idiom that uses the splat operator:
-
#
-
# [*object]
-
#
-
# which for +nil+ returns <tt>[nil]</tt> (Ruby 1.8.7) or <tt>[]</tt> (Ruby
-
# 1.9), and calls to <tt>Array(object)</tt> otherwise.
-
#
-
# Thus, in this case the behavior may be different for +nil+, and the differences with
-
# <tt>Kernel#Array</tt> explained above apply to the rest of <tt>object</tt>s.
-
1
def self.wrap(object)
-
534
if object.nil?
-
3
[]
-
531
elsif object.respond_to?(:to_ary)
-
525
object.to_ary || [object]
-
else
-
6
[object]
-
end
-
end
-
end
-
1
require 'benchmark'
-
-
1
class << Benchmark
-
1
def ms
-
10
1000 * realtime { yield }
-
end
-
end
-
1
require 'active_support/core_ext/big_decimal/conversions'
-
1
require 'bigdecimal'
-
1
require 'yaml'
-
-
1
class BigDecimal
-
1
YAML_MAPPING = { 'Infinity' => '.Inf', '-Infinity' => '-.Inf', 'NaN' => '.NaN' }
-
-
1
def encode_with(coder)
-
4
string = to_s
-
4
coder.represent_scalar(nil, YAML_MAPPING[string] || string)
-
end
-
-
# Backport this method if it doesn't exist
-
1
unless method_defined?(:to_d)
-
1
def to_d
-
self
-
end
-
end
-
-
1
DEFAULT_STRING_FORMAT = 'F'
-
1
def to_formatted_s(*args)
-
13
if args[0].is_a?(Symbol)
-
1
super
-
else
-
12
format = args[0] || DEFAULT_STRING_FORMAT
-
12
_original_to_s(format)
-
end
-
end
-
1
alias_method :_original_to_s, :to_s
-
1
alias_method :to_s, :to_formatted_s
-
end
-
1
require 'active_support/core_ext/class/attribute'
-
1
require 'active_support/core_ext/class/attribute_accessors'
-
1
require 'active_support/core_ext/class/delegating_attributes'
-
1
require 'active_support/core_ext/class/subclasses'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
class Class
-
# Declare a class-level attribute whose value is inheritable by subclasses.
-
# Subclasses can change their own value and it will not impact parent class.
-
#
-
# class Base
-
# class_attribute :setting
-
# end
-
#
-
# class Subclass < Base
-
# end
-
#
-
# Base.setting = true
-
# Subclass.setting # => true
-
# Subclass.setting = false
-
# Subclass.setting # => false
-
# Base.setting # => true
-
#
-
# In the above case as long as Subclass does not assign a value to setting
-
# by performing <tt>Subclass.setting = _something_ </tt>, <tt>Subclass.setting</tt>
-
# would read value assigned to parent class. Once Subclass assigns a value then
-
# the value assigned by Subclass would be returned.
-
#
-
# This matches normal Ruby method inheritance: think of writing an attribute
-
# on a subclass as overriding the reader method. However, you need to be aware
-
# when using +class_attribute+ with mutable structures as +Array+ or +Hash+.
-
# In such cases, you don't want to do changes in places but use setters:
-
#
-
# Base.setting = []
-
# Base.setting # => []
-
# Subclass.setting # => []
-
#
-
# # Appending in child changes both parent and child because it is the same object:
-
# Subclass.setting << :foo
-
# Base.setting # => [:foo]
-
# Subclass.setting # => [:foo]
-
#
-
# # Use setters to not propagate changes:
-
# Base.setting = []
-
# Subclass.setting += [:foo]
-
# Base.setting # => []
-
# Subclass.setting # => [:foo]
-
#
-
# For convenience, a query method is defined as well:
-
#
-
# Subclass.setting? # => false
-
#
-
# Instances may overwrite the class value in the same way:
-
#
-
# Base.setting = true
-
# object = Base.new
-
# object.setting # => true
-
# object.setting = false
-
# object.setting # => false
-
# Base.setting # => true
-
#
-
# To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
-
#
-
# object.setting # => NoMethodError
-
# object.setting? # => NoMethodError
-
#
-
# To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
-
#
-
# object.setting = false # => NoMethodError
-
#
-
# To opt out of both instance methods, pass <tt>instance_accessor: false</tt>.
-
1
def class_attribute(*attrs)
-
63
options = attrs.extract_options!
-
63
instance_reader = options.fetch(:instance_accessor, true) && options.fetch(:instance_reader, true)
-
63
instance_writer = options.fetch(:instance_accessor, true) && options.fetch(:instance_writer, true)
-
-
63
attrs.each do |name|
-
64
class_eval <<-RUBY, __FILE__, __LINE__ + 1
-
def self.#{name}() nil end
-
def self.#{name}?() !!#{name} end
-
-
def self.#{name}=(val)
-
singleton_class.class_eval do
-
remove_possible_method(:#{name})
-
define_method(:#{name}) { val }
-
end
-
-
if singleton_class?
-
class_eval do
-
remove_possible_method(:#{name})
-
def #{name}
-
defined?(@#{name}) ? @#{name} : singleton_class.#{name}
-
end
-
end
-
end
-
val
-
end
-
-
if instance_reader
-
remove_possible_method :#{name}
-
def #{name}
-
defined?(@#{name}) ? @#{name} : self.class.#{name}
-
end
-
-
def #{name}?
-
!!#{name}
-
end
-
end
-
RUBY
-
-
64
attr_writer name if instance_writer
-
end
-
end
-
-
1
private
-
1
def singleton_class?
-
164
ancestors.first != self
-
end
-
end
-
1
require 'active_support/core_ext/array/extract_options'
-
-
# Extends the class object with class and instance accessors for class attributes,
-
# just like the native attr* accessors for instance attributes.
-
1
class Class
-
# Defines a class attribute if it's not defined and creates a reader method that
-
# returns the attribute value.
-
#
-
# class Person
-
# cattr_reader :hair_colors
-
# end
-
#
-
# Person.class_variable_set("@@hair_colors", [:brown, :black])
-
# Person.hair_colors # => [:brown, :black]
-
# Person.new.hair_colors # => [:brown, :black]
-
#
-
# The attribute name must be a valid method name in Ruby.
-
#
-
# class Person
-
# cattr_reader :"1_Badname "
-
# end
-
# # => NameError: invalid attribute name
-
#
-
# If you want to opt out the instance reader method, you can pass <tt>instance_reader: false</tt>
-
# or <tt>instance_accessor: false</tt>.
-
#
-
# class Person
-
# cattr_reader :hair_colors, instance_reader: false
-
# end
-
#
-
# Person.new.hair_colors # => NoMethodError
-
1
def cattr_reader(*syms)
-
27
options = syms.extract_options!
-
27
syms.each do |sym|
-
27
raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\w*$/
-
26
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
unless defined? @@#{sym}
-
@@#{sym} = nil
-
end
-
-
def self.#{sym}
-
@@#{sym}
-
end
-
EOS
-
-
26
unless options[:instance_reader] == false || options[:instance_accessor] == false
-
14
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
def #{sym}
-
@@#{sym}
-
end
-
EOS
-
end
-
end
-
end
-
-
# Defines a class attribute if it's not defined and creates a writer method to allow
-
# assignment to the attribute.
-
#
-
# class Person
-
# cattr_writer :hair_colors
-
# end
-
#
-
# Person.hair_colors = [:brown, :black]
-
# Person.class_variable_get("@@hair_colors") # => [:brown, :black]
-
# Person.new.hair_colors = [:blonde, :red]
-
# Person.class_variable_get("@@hair_colors") # => [:blonde, :red]
-
#
-
# The attribute name must be a valid method name in Ruby.
-
#
-
# class Person
-
# cattr_writer :"1_Badname "
-
# end
-
# # => NameError: invalid attribute name
-
#
-
# If you want to opt out the instance writer method, pass <tt>instance_writer: false</tt>
-
# or <tt>instance_accessor: false</tt>.
-
#
-
# class Person
-
# cattr_writer :hair_colors, instance_writer: false
-
# end
-
#
-
# Person.new.hair_colors = [:blonde, :red] # => NoMethodError
-
#
-
# Also, you can pass a block to set up the attribute with a default value.
-
#
-
# class Person
-
# cattr_writer :hair_colors do
-
# [:brown, :black, :blonde, :red]
-
# end
-
# end
-
#
-
# Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]
-
1
def cattr_writer(*syms)
-
21
options = syms.extract_options!
-
21
syms.each do |sym|
-
21
raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\w*$/
-
20
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
unless defined? @@#{sym}
-
@@#{sym} = nil
-
end
-
-
def self.#{sym}=(obj)
-
@@#{sym} = obj
-
end
-
EOS
-
-
20
unless options[:instance_writer] == false || options[:instance_accessor] == false
-
8
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
def #{sym}=(obj)
-
@@#{sym} = obj
-
end
-
EOS
-
end
-
20
send("#{sym}=", yield) if block_given?
-
end
-
end
-
-
# Defines both class and instance accessors for class attributes.
-
#
-
# class Person
-
# cattr_accessor :hair_colors
-
# end
-
#
-
# Person.hair_colors = [:brown, :black, :blonde, :red]
-
# Person.hair_colors # => [:brown, :black, :blonde, :red]
-
# Person.new.hair_colors # => [:brown, :black, :blonde, :red]
-
#
-
# If a subclass changes the value then that would also change the value for
-
# parent class. Similarly if parent class changes the value then that would
-
# change the value of subclasses too.
-
#
-
# class Male < Person
-
# end
-
#
-
# Male.hair_colors << :blue
-
# Person.hair_colors # => [:brown, :black, :blonde, :red, :blue]
-
#
-
# To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
-
# To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
-
#
-
# class Person
-
# cattr_accessor :hair_colors, instance_writer: false, instance_reader: false
-
# end
-
#
-
# Person.new.hair_colors = [:brown] # => NoMethodError
-
# Person.new.hair_colors # => NoMethodError
-
#
-
# Or pass <tt>instance_accessor: false</tt>, to opt out both instance methods.
-
#
-
# class Person
-
# cattr_accessor :hair_colors, instance_accessor: false
-
# end
-
#
-
# Person.new.hair_colors = [:brown] # => NoMethodError
-
# Person.new.hair_colors # => NoMethodError
-
#
-
# Also you can pass a block to set up the attribute with a default value.
-
#
-
# class Person
-
# cattr_accessor :hair_colors do
-
# [:brown, :black, :blonde, :red]
-
# end
-
# end
-
#
-
# Person.class_variable_get("@@hair_colors") #=> [:brown, :black, :blonde, :red]
-
1
def cattr_accessor(*syms, &blk)
-
20
cattr_reader(*syms)
-
20
cattr_writer(*syms, &blk)
-
end
-
end
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'active_support/core_ext/module/remove_method'
-
-
1
class Class
-
1
def superclass_delegating_accessor(name, options = {})
-
# Create private _name and _name= methods that can still be used if the public
-
# methods are overridden. This allows
-
6
_superclass_delegating_accessor("_#{name}")
-
-
# Generate the public methods name, name=, and name?
-
# These methods dispatch to the private _name, and _name= methods, making them
-
# overridable
-
17
singleton_class.send(:define_method, name) { send("_#{name}") }
-
8
singleton_class.send(:define_method, "#{name}?") { !!send("_#{name}") }
-
15
singleton_class.send(:define_method, "#{name}=") { |value| send("_#{name}=", value) }
-
-
# If an instance_reader is needed, generate methods for name and name= on the
-
# class itself, so instances will be able to see them
-
8
define_method(name) { send("_#{name}") } if options[:instance_reader] != false
-
7
define_method("#{name}?") { !!send("#{name}") } if options[:instance_reader] != false
-
end
-
-
1
private
-
# Take the object being set and store it in a method. This gives us automatic
-
# inheritance behavior, without having to store the object in an instance
-
# variable and look up the superclass chain manually.
-
1
def _stash_object_in_method(object, method, instance_reader = true)
-
15
singleton_class.remove_possible_method(method)
-
28
singleton_class.send(:define_method, method) { object }
-
15
remove_possible_method(method)
-
17
define_method(method) { object } if instance_reader
-
end
-
-
1
def _superclass_delegating_accessor(name, options = {})
-
6
singleton_class.send(:define_method, "#{name}=") do |value|
-
15
_stash_object_in_method(value, name, options[:instance_reader] != false)
-
end
-
6
send("#{name}=", nil)
-
end
-
end
-
1
require 'active_support/core_ext/module/anonymous'
-
1
require 'active_support/core_ext/module/reachable'
-
-
1
class Class
-
1
begin
-
1
ObjectSpace.each_object(Class.new) {}
-
-
1
def descendants # :nodoc:
-
8
descendants = []
-
8
ObjectSpace.each_object(singleton_class) do |k|
-
26
descendants.unshift k unless k == self
-
end
-
8
descendants
-
end
-
rescue StandardError # JRuby
-
def descendants # :nodoc:
-
descendants = []
-
ObjectSpace.each_object(Class) do |k|
-
descendants.unshift k if k < self
-
end
-
descendants.uniq!
-
descendants
-
end
-
end
-
-
# Returns an array with the direct children of +self+.
-
#
-
# Integer.subclasses # => [Fixnum, Bignum]
-
#
-
# class Foo; end
-
# class Bar < Foo; end
-
# class Baz < Foo; end
-
#
-
# Foo.subclasses # => [Baz, Bar]
-
1
def subclasses
-
4
subclasses, chain = [], descendants
-
4
chain.each do |k|
-
37
subclasses << k unless chain.any? { |c| c > k }
-
end
-
4
subclasses
-
end
-
end
-
1
require 'active_support/core_ext/date/acts_like'
-
1
require 'active_support/core_ext/date/calculations'
-
1
require 'active_support/core_ext/date/conversions'
-
1
require 'active_support/core_ext/date/zones'
-
-
1
require 'active_support/core_ext/object/acts_like'
-
-
1
class Date
-
# Duck-types as a Date-like class. See Object#acts_like?.
-
1
def acts_like_date?
-
1
true
-
end
-
end
-
1
require 'date'
-
1
require 'active_support/duration'
-
1
require 'active_support/core_ext/object/acts_like'
-
1
require 'active_support/core_ext/date/zones'
-
1
require 'active_support/core_ext/time/zones'
-
1
require 'active_support/core_ext/date_and_time/calculations'
-
-
1
class Date
-
1
include DateAndTime::Calculations
-
-
1
@beginning_of_week_default = nil
-
-
1
class << self
-
1
attr_accessor :beginning_of_week_default
-
-
# Returns the week start (e.g. :monday) for the current request, if this has been set (via Date.beginning_of_week=).
-
# If <tt>Date.beginning_of_week</tt> has not been set for the current request, returns the week start specified in <tt>config.beginning_of_week</tt>.
-
# If no config.beginning_of_week was specified, returns :monday.
-
1
def beginning_of_week
-
254
Thread.current[:beginning_of_week] || beginning_of_week_default || :monday
-
end
-
-
# Sets <tt>Date.beginning_of_week</tt> to a week start (e.g. :monday) for current request/thread.
-
#
-
# This method accepts any of the following day symbols:
-
# :monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday
-
1
def beginning_of_week=(week_start)
-
30
Thread.current[:beginning_of_week] = find_beginning_of_week!(week_start)
-
end
-
-
# Returns week start day symbol (e.g. :monday), or raises an ArgumentError for invalid day symbol.
-
1
def find_beginning_of_week!(week_start)
-
30
raise ArgumentError, "Invalid beginning of week: #{week_start}" unless ::Date::DAYS_INTO_WEEK.key?(week_start)
-
30
week_start
-
end
-
-
# Returns a new Date representing the date 1 day ago (i.e. yesterday's date).
-
1
def yesterday
-
3
::Date.current.yesterday
-
end
-
-
# Returns a new Date representing the date 1 day after today (i.e. tomorrow's date).
-
1
def tomorrow
-
3
::Date.current.tomorrow
-
end
-
-
# Returns Time.zone.today when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns Date.today.
-
1
def current
-
10
::Time.zone ? ::Time.zone.today : ::Date.today
-
end
-
end
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
-
# and then subtracts the specified number of seconds.
-
1
def ago(seconds)
-
3
to_time_in_current_zone.since(-seconds)
-
end
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
-
# and then adds the specified number of seconds
-
1
def since(seconds)
-
6
to_time_in_current_zone.since(seconds)
-
end
-
1
alias :in :since
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00)
-
1
def beginning_of_day
-
3
to_time_in_current_zone
-
end
-
1
alias :midnight :beginning_of_day
-
1
alias :at_midnight :beginning_of_day
-
1
alias :at_beginning_of_day :beginning_of_day
-
-
# Converts Date to a Time (or DateTime if necessary) with the time portion set to the end of the day (23:59:59)
-
1
def end_of_day
-
3
to_time_in_current_zone.end_of_day
-
end
-
-
1
def plus_with_duration(other) #:nodoc:
-
658
if ActiveSupport::Duration === other
-
19
other.since(self)
-
else
-
639
plus_without_duration(other)
-
end
-
end
-
1
alias_method :plus_without_duration, :+
-
1
alias_method :+, :plus_with_duration
-
-
1
def minus_with_duration(other) #:nodoc:
-
5
if ActiveSupport::Duration === other
-
2
plus_with_duration(-other)
-
else
-
3
minus_without_duration(other)
-
end
-
end
-
1
alias_method :minus_without_duration, :-
-
1
alias_method :-, :minus_with_duration
-
-
# Provides precise Date calculations for years, months, and days. The +options+ parameter takes a hash with
-
# any of these keys: <tt>:years</tt>, <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>.
-
1
def advance(options)
-
794
options = options.dup
-
794
d = self
-
794
d = d >> options.delete(:years) * 12 if options[:years]
-
794
d = d >> options.delete(:months) if options[:months]
-
794
d = d + options.delete(:weeks) * 7 if options[:weeks]
-
794
d = d + options.delete(:days) if options[:days]
-
794
d
-
end
-
-
# Returns a new Date where one or more of the elements have been changed according to the +options+ parameter.
-
# The +options+ parameter is a hash with a combination of these keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>.
-
#
-
# Date.new(2007, 5, 12).change(day: 1) # => Date.new(2007, 5, 1)
-
# Date.new(2007, 5, 12).change(year: 2005, month: 1) # => Date.new(2005, 1, 12)
-
1
def change(options)
-
26
::Date.new(
-
options.fetch(:year, year),
-
options.fetch(:month, month),
-
options.fetch(:day, day)
-
)
-
end
-
end
-
1
require 'date'
-
1
require 'active_support/inflector/methods'
-
1
require 'active_support/core_ext/date/zones'
-
1
require 'active_support/core_ext/module/remove_method'
-
-
1
class Date
-
1
DATE_FORMATS = {
-
:short => '%e %b',
-
:long => '%B %e, %Y',
-
:db => '%Y-%m-%d',
-
:number => '%Y%m%d',
-
:long_ordinal => lambda { |date|
-
1
day_format = ActiveSupport::Inflector.ordinalize(date.day)
-
1
date.strftime("%B #{day_format}, %Y") # => "April 25th, 2007"
-
},
-
:rfc822 => '%e %b %Y'
-
}
-
-
# Ruby 1.9 has Date#to_time which converts to localtime only.
-
1
remove_possible_method :to_time
-
-
# Ruby 1.9 has Date#xmlschema which converts to a string without the time component.
-
1
remove_possible_method :xmlschema
-
-
# Convert to a formatted string. See DATE_FORMATS for predefined formats.
-
#
-
# This method is aliased to <tt>to_s</tt>.
-
#
-
# date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007
-
#
-
# date.to_formatted_s(:db) # => "2007-11-10"
-
# date.to_s(:db) # => "2007-11-10"
-
#
-
# date.to_formatted_s(:short) # => "10 Nov"
-
# date.to_formatted_s(:long) # => "November 10, 2007"
-
# date.to_formatted_s(:long_ordinal) # => "November 10th, 2007"
-
# date.to_formatted_s(:rfc822) # => "10 Nov 2007"
-
#
-
# == Adding your own time formats to to_formatted_s
-
# You can add your own formats to the Date::DATE_FORMATS hash.
-
# Use the format name as the hash key and either a strftime string
-
# or Proc instance that takes a date argument as the value.
-
#
-
# # config/initializers/time_formats.rb
-
# Date::DATE_FORMATS[:month_and_year] = '%B %Y'
-
# Date::DATE_FORMATS[:short_ordinal] = ->(date) { date.strftime("%B #{date.day.ordinalize}") }
-
1
def to_formatted_s(format = :default)
-
11
if formatter = DATE_FORMATS[format]
-
8
if formatter.respond_to?(:call)
-
1
formatter.call(self).to_s
-
else
-
7
strftime(formatter)
-
end
-
else
-
3
to_default_s
-
end
-
end
-
1
alias_method :to_default_s, :to_s
-
1
alias_method :to_s, :to_formatted_s
-
-
# Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005"
-
1
def readable_inspect
-
4
strftime('%a, %d %b %Y')
-
end
-
1
alias_method :default_inspect, :inspect
-
1
alias_method :inspect, :readable_inspect
-
-
# Converts a Date instance to a Time, where the time is set to the beginning of the day.
-
# The timezone can be either :local or :utc (default :local).
-
#
-
# date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007
-
#
-
# date.to_time # => Sat Nov 10 00:00:00 0800 2007
-
# date.to_time(:local) # => Sat Nov 10 00:00:00 0800 2007
-
#
-
# date.to_time(:utc) # => Sat Nov 10 00:00:00 UTC 2007
-
1
def to_time(form = :local)
-
293
::Time.send("#{form}_time", year, month, day)
-
end
-
-
1
def xmlschema
-
4
to_time_in_current_zone.xmlschema
-
end
-
end
-
1
require 'date'
-
1
require 'active_support/core_ext/time/zones'
-
-
1
class Date
-
# Converts Date to a TimeWithZone in the current zone if <tt>Time.zone</tt> or
-
# <tt>Time.zone_default</tt> is set, otherwise converts Date to a Time via
-
# Date#to_time.
-
1
def to_time_in_current_zone
-
19
if ::Time.zone
-
10
::Time.zone.local(year, month, day)
-
else
-
9
to_time
-
end
-
end
-
end
-
1
module DateAndTime
-
1
module Calculations
-
1
DAYS_INTO_WEEK = {
-
:monday => 0,
-
:tuesday => 1,
-
:wednesday => 2,
-
:thursday => 3,
-
:friday => 4,
-
:saturday => 5,
-
:sunday => 6
-
}
-
-
# Returns a new date/time representing yesterday.
-
1
def yesterday
-
21
advance(:days => -1)
-
end
-
-
# Returns a new date/time representing tomorrow.
-
1
def tomorrow
-
21
advance(:days => 1)
-
end
-
-
# Returns true if the date/time is today.
-
1
def today?
-
20
to_date == ::Date.current
-
end
-
-
# Returns true if the date/time is in the past.
-
1
def past?
-
21
self < self.class.current
-
end
-
-
# Returns true if the date/time is in the future.
-
1
def future?
-
21
self > self.class.current
-
end
-
-
# Returns a new date/time the specified number of days ago.
-
1
def days_ago(days)
-
108
advance(:days => -days)
-
end
-
-
# Returns a new date/time the specified number of days in the future.
-
1
def days_since(days)
-
144
advance(:days => days)
-
end
-
-
# Returns a new date/time the specified number of weeks ago.
-
1
def weeks_ago(weeks)
-
57
advance(:weeks => -weeks)
-
end
-
-
# Returns a new date/time the specified number of weeks in the future.
-
1
def weeks_since(weeks)
-
42
advance(:weeks => weeks)
-
end
-
-
# Returns a new date/time the specified number of months ago.
-
1
def months_ago(months)
-
27
advance(:months => -months)
-
end
-
-
# Returns a new date/time the specified number of months in the future.
-
1
def months_since(months)
-
44
advance(:months => months)
-
end
-
-
# Returns a new date/time the specified number of years ago.
-
1
def years_ago(years)
-
17
advance(:years => -years)
-
end
-
-
# Returns a new date/time the specified number of years in the future.
-
1
def years_since(years)
-
16
advance(:years => years)
-
end
-
-
# Returns a new date/time at the start of the month.
-
# DateTime objects will have a time set to 0:00.
-
1
def beginning_of_month
-
78
first_hour{ change(:day => 1) }
-
end
-
1
alias :at_beginning_of_month :beginning_of_month
-
-
# Returns a new date/time at the start of the quarter.
-
# Example: 1st January, 1st July, 1st October.
-
# DateTime objects will have a time set to 0:00.
-
1
def beginning_of_quarter
-
52
first_quarter_month = [10, 7, 4, 1].detect { |m| m <= month }
-
13
beginning_of_month.change(:month => first_quarter_month)
-
end
-
1
alias :at_beginning_of_quarter :beginning_of_quarter
-
-
# Returns a new date/time at the end of the quarter.
-
# Example: 31st March, 30th June, 30th September.
-
# DateTIme objects will have a time set to 23:59:59.
-
1
def end_of_quarter
-
48
last_quarter_month = [3, 6, 9, 12].detect { |m| m >= month }
-
16
beginning_of_month.change(:month => last_quarter_month).end_of_month
-
end
-
1
alias :at_end_of_quarter :end_of_quarter
-
-
# Return a new date/time at the beginning of the year.
-
# Example: 1st January.
-
# DateTime objects will have a time set to 0:00.
-
1
def beginning_of_year
-
5
change(:month => 1).beginning_of_month
-
end
-
1
alias :at_beginning_of_year :beginning_of_year
-
-
# Returns a new date/time representing the given day in the next week.
-
# Week is assumed to start on +start_day+, default is
-
# +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
-
# DateTime objects have their time set to 0:00.
-
1
def next_week(start_day = Date.beginning_of_week)
-
60
first_hour{ weeks_since(1).beginning_of_week.days_since(days_span(start_day)) }
-
end
-
-
# Short-hand for months_since(1).
-
1
def next_month
-
1
months_since(1)
-
end
-
-
# Short-hand for months_since(3)
-
1
def next_quarter
-
3
months_since(3)
-
end
-
-
# Short-hand for years_since(1).
-
1
def next_year
-
1
years_since(1)
-
end
-
-
# Returns a new date/time representing the given day in the previous week.
-
# Week is assumed to start on +start_day+, default is
-
# +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
-
# DateTime objects have their time set to 0:00.
-
1
def prev_week(start_day = Date.beginning_of_week)
-
84
first_hour{ weeks_ago(1).beginning_of_week.days_since(days_span(start_day)) }
-
end
-
1
alias_method :last_week, :prev_week
-
-
# Short-hand for months_ago(1).
-
1
def prev_month
-
4
months_ago(1)
-
end
-
1
alias_method :last_month, :prev_month
-
-
# Short-hand for months_ago(3).
-
1
def prev_quarter
-
6
months_ago(3)
-
end
-
1
alias_method :last_quarter, :prev_quarter
-
-
# Short-hand for years_ago(1).
-
1
def prev_year
-
6
years_ago(1)
-
end
-
1
alias_method :last_year, :prev_year
-
-
# Returns the number of days to the start of the week on the given day.
-
# Week is assumed to start on +start_day+, default is
-
# +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
-
1
def days_to_week_start(start_day = Date.beginning_of_week)
-
197
start_day_number = DAYS_INTO_WEEK[start_day]
-
197
current_day_number = wday != 0 ? wday - 1 : 6
-
197
(current_day_number - start_day_number) % 7
-
end
-
-
# Returns a new date/time representing the start of this week on the given day.
-
# Week is assumed to start on +start_day+, default is
-
# +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
-
# +DateTime+ objects have their time set to 0:00.
-
1
def beginning_of_week(start_day = Date.beginning_of_week)
-
102
result = days_ago(days_to_week_start(start_day))
-
102
acts_like?(:time) ? result.midnight : result
-
end
-
1
alias :at_beginning_of_week :beginning_of_week
-
-
# Returns Monday of this week assuming that week starts on Monday.
-
# +DateTime+ objects have their time set to 0:00.
-
1
def monday
-
3
beginning_of_week(:monday)
-
end
-
-
# Returns a new date/time representing the end of this week on the given day.
-
# Week is assumed to start on +start_day+, default is
-
# +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
-
# DateTime objects have their time set to 23:59:59.
-
1
def end_of_week(start_day = Date.beginning_of_week)
-
64
last_hour{ days_since(6 - days_to_week_start(start_day)) }
-
end
-
1
alias :at_end_of_week :end_of_week
-
-
# Returns Sunday of this week assuming that week starts on Monday.
-
# +DateTime+ objects have their time set to 23:59:59.
-
1
def sunday
-
5
end_of_week(:monday)
-
end
-
-
# Returns a new date/time representing the end of the month.
-
# DateTime objects will have a time set to 23:59:59.
-
1
def end_of_month
-
34
last_day = ::Time.days_in_month(month, year)
-
68
last_hour{ days_since(last_day - day) }
-
end
-
1
alias :at_end_of_month :end_of_month
-
-
# Returns a new date/time representing the end of the year.
-
# DateTime objects will have a time set to 23:59:59.
-
1
def end_of_year
-
7
change(:month => 12).end_of_month
-
end
-
1
alias :at_end_of_year :end_of_year
-
-
1
private
-
-
1
def first_hour
-
111
result = yield
-
111
acts_like?(:time) ? result.change(:hour => 0) : result
-
end
-
-
1
def last_hour
-
66
result = yield
-
66
acts_like?(:time) ? result.end_of_day : result
-
end
-
-
1
def days_span(day)
-
72
(DAYS_INTO_WEEK[day] - DAYS_INTO_WEEK[Date.beginning_of_week]) % 7
-
end
-
end
-
end
-
1
require 'active_support/core_ext/date_time/acts_like'
-
1
require 'active_support/core_ext/date_time/calculations'
-
1
require 'active_support/core_ext/date_time/conversions'
-
1
require 'active_support/core_ext/date_time/zones'
-
1
require 'active_support/core_ext/object/acts_like'
-
-
1
class DateTime
-
# Duck-types as a Date-like class. See Object#acts_like?.
-
1
def acts_like_date?
-
true
-
end
-
-
# Duck-types as a Time-like class. See Object#acts_like?.
-
1
def acts_like_time?
-
1
true
-
end
-
end
-
1
require 'active_support/deprecation'
-
-
1
class DateTime
-
1
class << self
-
# *DEPRECATED*: Use +DateTime.civil_from_format+ directly.
-
1
def local_offset
-
ActiveSupport::Deprecation.warn 'DateTime.local_offset is deprecated. Use DateTime.civil_from_format directly.'
-
-
::Time.local(2012).utc_offset.to_r / 86400
-
end
-
-
# Returns <tt>Time.zone.now.to_datetime</tt> when <tt>Time.zone</tt> or
-
# <tt>config.time_zone</tt> are set, otherwise returns
-
# <tt>Time.now.to_datetime</tt>.
-
1
def current
-
4
::Time.zone ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime
-
end
-
end
-
-
# Tells whether the DateTime object's datetime lies in the past.
-
1
def past?
-
6
self < ::DateTime.current
-
end
-
-
# Tells whether the DateTime object's datetime lies in the future.
-
1
def future?
-
6
self > ::DateTime.current
-
end
-
-
# Seconds since midnight: DateTime.now.seconds_since_midnight.
-
1
def seconds_since_midnight
-
17
sec + (min * 60) + (hour * 3600)
-
end
-
-
# Returns a new DateTime where one or more of the elements have been changed
-
# according to the +options+ parameter. The time options (<tt>:hour</tt>,
-
# <tt>:minute</tt>, <tt>:sec</tt>) reset cascadingly, so if only the hour is
-
# passed, then minute and sec is set to 0. If the hour and minute is passed,
-
# then sec is set to 0. The +options+ parameter takes a hash with any of these
-
# keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>,
-
# <tt>:min</tt>, <tt>:sec</tt>, <tt>:offset</tt>, <tt>:start</tt>.
-
#
-
# DateTime.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => DateTime.new(2012, 8, 1, 22, 35, 0)
-
# DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => DateTime.new(1981, 8, 1, 22, 35, 0)
-
# DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => DateTime.new(1981, 8, 29, 0, 0, 0)
-
1
def change(options)
-
266
::DateTime.civil(
-
options.fetch(:year, year),
-
options.fetch(:month, month),
-
options.fetch(:day, day),
-
options.fetch(:hour, hour),
-
options.fetch(:min, options[:hour] ? 0 : min),
-
options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec),
-
options.fetch(:offset, offset),
-
options.fetch(:start, start)
-
)
-
end
-
-
# Uses Date to provide precise Time calculations for years, months, and days.
-
# The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>,
-
# <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>,
-
# <tt>:minutes</tt>, <tt>:seconds</tt>.
-
1
def advance(options)
-
166
d = to_date.advance(options)
-
166
datetime_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
-
166
seconds_to_advance = \
-
options.fetch(:seconds, 0) +
-
options.fetch(:minutes, 0) * 60 +
-
options.fetch(:hours, 0) * 3600
-
-
166
if seconds_to_advance.zero?
-
156
datetime_advanced_by_date
-
else
-
10
datetime_advanced_by_date.since seconds_to_advance
-
end
-
end
-
-
# Returns a new DateTime representing the time a number of seconds ago.
-
# Do not use this method in combination with x.months, use months_ago instead!
-
1
def ago(seconds)
-
5
since(-seconds)
-
end
-
-
# Returns a new DateTime representing the time a number of seconds since the
-
# instance time. Do not use this method in combination with x.months, use
-
# months_since instead!
-
1
def since(seconds)
-
28
self + Rational(seconds.round, 86400)
-
end
-
1
alias :in :since
-
-
# Returns a new DateTime representing the start of the day (0:00).
-
1
def beginning_of_day
-
24
change(:hour => 0)
-
end
-
1
alias :midnight :beginning_of_day
-
1
alias :at_midnight :beginning_of_day
-
1
alias :at_beginning_of_day :beginning_of_day
-
-
# Returns a new DateTime representing the end of the day (23:59:59).
-
1
def end_of_day
-
20
change(:hour => 23, :min => 59, :sec => 59)
-
end
-
-
# Returns a new DateTime representing the start of the hour (hh:00:00).
-
1
def beginning_of_hour
-
1
change(:min => 0)
-
end
-
1
alias :at_beginning_of_hour :beginning_of_hour
-
-
# Returns a new DateTime representing the end of the hour (hh:59:59).
-
1
def end_of_hour
-
1
change(:min => 59, :sec => 59)
-
end
-
-
# Adjusts DateTime to UTC by adding its offset value; offset is set to 0.
-
#
-
# DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)) # => Mon, 21 Feb 2005 10:11:12 -0600
-
# DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)).utc # => Mon, 21 Feb 2005 16:11:12 +0000
-
1
def utc
-
11
new_offset(0)
-
end
-
1
alias_method :getutc, :utc
-
-
# Returns +true+ if <tt>offset == 0</tt>.
-
1
def utc?
-
27
offset == 0
-
end
-
-
# Returns the offset value in seconds.
-
1
def utc_offset
-
13
(offset * 86400).to_i
-
end
-
-
# Layers additional behavior on DateTime#<=> so that Time and
-
# ActiveSupport::TimeWithZone instances can be compared with a DateTime.
-
1
def <=>(other)
-
340
super other.to_datetime
-
end
-
-
end
-
1
require 'active_support/inflector/methods'
-
1
require 'active_support/core_ext/time/conversions'
-
1
require 'active_support/core_ext/date_time/calculations'
-
1
require 'active_support/values/time_zone'
-
-
1
class DateTime
-
# Convert to a formatted string. See Time::DATE_FORMATS for predefined formats.
-
#
-
# This method is aliased to <tt>to_s</tt>.
-
#
-
# === Examples
-
# datetime = DateTime.civil(2007, 12, 4, 0, 0, 0, 0) # => Tue, 04 Dec 2007 00:00:00 +0000
-
#
-
# datetime.to_formatted_s(:db) # => "2007-12-04 00:00:00"
-
# datetime.to_s(:db) # => "2007-12-04 00:00:00"
-
# datetime.to_s(:number) # => "20071204000000"
-
# datetime.to_formatted_s(:short) # => "04 Dec 00:00"
-
# datetime.to_formatted_s(:long) # => "December 04, 2007 00:00"
-
# datetime.to_formatted_s(:long_ordinal) # => "December 4th, 2007 00:00"
-
# datetime.to_formatted_s(:rfc822) # => "Tue, 04 Dec 2007 00:00:00 +0000"
-
#
-
# == Adding your own datetime formats to to_formatted_s
-
# DateTime formats are shared with Time. You can add your own to the
-
# Time::DATE_FORMATS hash. Use the format name as the hash key and
-
# either a strftime string or Proc instance that takes a time or
-
# datetime argument as the value.
-
#
-
# # config/initializers/time_formats.rb
-
# Time::DATE_FORMATS[:month_and_year] = '%B %Y'
-
# Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") }
-
1
def to_formatted_s(format = :default)
-
11
if formatter = ::Time::DATE_FORMATS[format]
-
10
formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
-
else
-
1
to_default_s
-
end
-
end
-
1
alias_method :to_default_s, :to_s if instance_methods(false).include?(:to_s)
-
1
alias_method :to_s, :to_formatted_s
-
-
#
-
# datetime = DateTime.civil(2000, 1, 1, 0, 0, 0, Rational(-6, 24))
-
# datetime.formatted_offset # => "-06:00"
-
# datetime.formatted_offset(false) # => "-0600"
-
1
def formatted_offset(colon = true, alternate_utc_string = nil)
-
9
utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon)
-
end
-
-
# Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005 14:30:00 +0000".
-
1
def readable_inspect
-
3
to_s(:rfc822)
-
end
-
1
alias_method :default_inspect, :inspect
-
1
alias_method :inspect, :readable_inspect
-
-
# Returns DateTime with local offset for given year if format is local else
-
# offset is zero.
-
#
-
# DateTime.civil_from_format :local, 2012
-
# # => Sun, 01 Jan 2012 00:00:00 +0300
-
# DateTime.civil_from_format :local, 2012, 12, 17
-
# # => Mon, 17 Dec 2012 00:00:00 +0000
-
1
def self.civil_from_format(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0)
-
4
if utc_or_local.to_sym == :local
-
3
offset = ::Time.local(year, month, day).utc_offset.to_r / 86400
-
else
-
1
offset = 0
-
end
-
4
civil(year, month, day, hour, min, sec, offset)
-
end
-
-
# Converts +self+ to a floating-point number of seconds since the Unix epoch.
-
1
def to_f
-
10
seconds_since_unix_epoch.to_f
-
end
-
-
# Converts +self+ to an integer number of seconds since the Unix epoch.
-
1
def to_i
-
3
seconds_since_unix_epoch.to_i
-
end
-
-
1
private
-
-
1
def offset_in_seconds
-
13
(offset * 86400).to_i
-
end
-
-
1
def seconds_since_unix_epoch
-
13
(jd - 2440588) * 86400 - offset_in_seconds + seconds_since_midnight
-
end
-
end
-
1
require 'active_support/core_ext/time/zones'
-
-
1
class DateTime
-
# Returns the simultaneous time in <tt>Time.zone</tt>.
-
#
-
# Time.zone = 'Hawaii' # => 'Hawaii'
-
# DateTime.new(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
#
-
# This method is similar to Time#localtime, except that it uses <tt>Time.zone</tt>
-
# as the local zone instead of the operating system's time zone.
-
#
-
# You can also pass in a TimeZone instance or string that identifies a TimeZone
-
# as an argument, and the conversion will be based on that zone instead of
-
# <tt>Time.zone</tt>.
-
#
-
# DateTime.new(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
-
1
def in_time_zone(zone = ::Time.zone)
-
14
if zone
-
12
ActiveSupport::TimeWithZone.new(utc? ? self : getutc, ::Time.find_zone!(zone))
-
else
-
2
self
-
end
-
end
-
end
-
1
module Enumerable
-
# Calculates a sum from the elements.
-
#
-
# payments.sum { |p| p.price * p.tax_rate }
-
# payments.sum(&:price)
-
#
-
# The latter is a shortcut for:
-
#
-
# payments.inject(0) { |sum, p| sum + p.price }
-
#
-
# It can also calculate the sum without the use of a block.
-
#
-
# [5, 15, 10].sum # => 30
-
# ['foo', 'bar'].sum # => "foobar"
-
# [[1, 2], [3, 1, 5]].sum => [1, 2, 3, 1, 5]
-
#
-
# The default sum of an empty list is zero. You can override this default:
-
#
-
# [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)
-
1
def sum(identity = 0, &block)
-
26
if block_given?
-
9
map(&block).sum(identity)
-
else
-
47
inject { |sum, element| sum + element } || identity
-
end
-
end
-
-
# Convert an enumerable to a hash.
-
#
-
# people.index_by(&:login)
-
# => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...}
-
# people.index_by { |person| "#{person.first_name} #{person.last_name}" }
-
# => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...}
-
1
def index_by
-
4
if block_given?
-
8
Hash[map { |elem| [yield(elem), elem] }]
-
else
-
2
to_enum :index_by
-
end
-
end
-
-
# Returns +true+ if the enumerable has more than 1 element. Functionally
-
# equivalent to <tt>enum.to_a.size > 1</tt>. Can be called with a block too,
-
# much like any?, so <tt>people.many? { |p| p.age > 26 }</tt> returns +true+
-
# if more than one person is over 26.
-
1
def many?
-
9
cnt = 0
-
9
if block_given?
-
5
any? do |element|
-
109
cnt += 1 if yield element
-
109
cnt > 1
-
end
-
else
-
9
any? { (cnt += 1) > 1 }
-
end
-
end
-
-
# The negative of the <tt>Enumerable#include?</tt>. Returns +true+ if the
-
# collection does not include the object.
-
1
def exclude?(object)
-
2
!include?(object)
-
end
-
end
-
-
1
class Range #:nodoc:
-
# Optimize range sum to use arithmetic progression if a block is not given and
-
# we have a range of numeric values.
-
1
def sum(identity = 0)
-
10
if block_given? || !(first.is_a?(Integer) && last.is_a?(Integer))
-
3
super
-
else
-
7
actual_last = exclude_end? ? (last - 1) : last
-
7
if actual_last >= first
-
4
(actual_last - first + 1) * (actual_last + first) / 2
-
else
-
3
identity
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
1
FrozenObjectError = RuntimeError
-
end
-
1
require 'active_support/core_ext/file/atomic'
-
1
require 'fileutils'
-
-
1
class File
-
# Write to a file atomically. Useful for situations where you don't
-
# want other processes or threads to see half-written files.
-
#
-
# File.atomic_write('important.file') do |file|
-
# file.write('hello')
-
# end
-
#
-
# If your temp directory is not on the same filesystem as the file you're
-
# trying to write, you can provide a different temporary directory.
-
#
-
# File.atomic_write('/data/something.important', '/data/tmp') do |file|
-
# file.write('hello')
-
# end
-
1
def self.atomic_write(file_name, temp_dir = Dir.tmpdir)
-
64
require 'tempfile' unless defined?(Tempfile)
-
64
require 'fileutils' unless defined?(FileUtils)
-
-
64
temp_file = Tempfile.new(basename(file_name), temp_dir)
-
63
temp_file.binmode
-
63
yield temp_file
-
62
temp_file.close
-
-
62
if File.exists?(file_name)
-
# Get original file permissions
-
11
old_stat = stat(file_name)
-
else
-
# If not possible, probe which are the default permissions in the
-
# destination directory.
-
51
old_stat = probe_stat_in(dirname(file_name))
-
end
-
-
# Overwrite original file with temp file
-
62
FileUtils.mv(temp_file.path, file_name)
-
-
# Set correct permissions on new file
-
58
begin
-
58
chown(old_stat.uid, old_stat.gid, file_name)
-
# This operation will affect filesystem ACL's
-
58
chmod(old_stat.mode, file_name)
-
rescue Errno::EPERM
-
# Changing file ownership failed, moving on.
-
end
-
end
-
-
# Private utility method.
-
1
def self.probe_stat_in(dir) #:nodoc:
-
52
basename = [
-
'.permissions_check',
-
Thread.current.object_id,
-
Process.pid,
-
rand(1000000)
-
].join('.')
-
-
52
file_name = join(dir, basename)
-
52
FileUtils.touch(file_name)
-
52
stat(file_name)
-
ensure
-
52
FileUtils.rm_f(file_name) if file_name
-
end
-
end
-
1
require 'active_support/core_ext/hash/conversions'
-
1
require 'active_support/core_ext/hash/deep_merge'
-
1
require 'active_support/core_ext/hash/diff'
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/hash/indifferent_access'
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/core_ext/hash/reverse_merge'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/xml_mini'
-
1
require 'active_support/time'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/core_ext/object/to_param'
-
1
require 'active_support/core_ext/object/to_query'
-
1
require 'active_support/core_ext/array/wrap'
-
1
require 'active_support/core_ext/hash/reverse_merge'
-
1
require 'active_support/core_ext/string/inflections'
-
-
1
class Hash
-
# Returns a string containing an XML representation of its receiver:
-
#
-
# {'foo' => 1, 'bar' => 2}.to_xml
-
# # =>
-
# # <?xml version="1.0" encoding="UTF-8"?>
-
# # <hash>
-
# # <foo type="integer">1</foo>
-
# # <bar type="integer">2</bar>
-
# # </hash>
-
#
-
# To do so, the method loops over the pairs and builds nodes that depend on
-
# the _values_. Given a pair +key+, +value+:
-
#
-
# * If +value+ is a hash there's a recursive call with +key+ as <tt>:root</tt>.
-
#
-
# * If +value+ is an array there's a recursive call with +key+ as <tt>:root</tt>,
-
# and +key+ singularized as <tt>:children</tt>.
-
#
-
# * If +value+ is a callable object it must expect one or two arguments. Depending
-
# on the arity, the callable is invoked with the +options+ hash as first argument
-
# with +key+ as <tt>:root</tt>, and +key+ singularized as second argument. The
-
# callable can add nodes by using <tt>options[:builder]</tt>.
-
#
-
# 'foo'.to_xml(lambda { |options, key| options[:builder].b(key) })
-
# # => "<b>foo</b>"
-
#
-
# * If +value+ responds to +to_xml+ the method is invoked with +key+ as <tt>:root</tt>.
-
#
-
# class Foo
-
# def to_xml(options)
-
# options[:builder].bar 'fooing!'
-
# end
-
# end
-
#
-
# { foo: Foo.new }.to_xml(skip_instruct: true)
-
# # => "<hash><bar>fooing!</bar></hash>"
-
#
-
# * Otherwise, a node with +key+ as tag is created with a string representation of
-
# +value+ as text node. If +value+ is +nil+ an attribute "nil" set to "true" is added.
-
# Unless the option <tt>:skip_types</tt> exists and is true, an attribute "type" is
-
# added as well according to the following mapping:
-
#
-
# XML_TYPE_NAMES = {
-
# "Symbol" => "symbol",
-
# "Fixnum" => "integer",
-
# "Bignum" => "integer",
-
# "BigDecimal" => "decimal",
-
# "Float" => "float",
-
# "TrueClass" => "boolean",
-
# "FalseClass" => "boolean",
-
# "Date" => "date",
-
# "DateTime" => "dateTime",
-
# "Time" => "dateTime"
-
# }
-
#
-
# By default the root node is "hash", but that's configurable via the <tt>:root</tt> option.
-
#
-
# The default XML builder is a fresh instance of <tt>Builder::XmlMarkup</tt>. You can
-
# configure your own builder with the <tt>:builder</tt> option. The method also accepts
-
# options like <tt>:dasherize</tt> and friends, they are forwarded to the builder.
-
1
def to_xml(options = {})
-
40
require 'active_support/builder' unless defined?(Builder)
-
-
40
options = options.dup
-
40
options[:indent] ||= 2
-
40
options[:root] ||= 'hash'
-
40
options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent])
-
-
40
builder = options[:builder]
-
40
builder.instruct! unless options.delete(:skip_instruct)
-
-
40
root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options)
-
-
40
builder.tag!(root) do
-
123
each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, options) }
-
40
yield builder if block_given?
-
end
-
end
-
-
1
class << self
-
1
def from_xml(xml)
-
26
typecast_xml_value(unrename_keys(ActiveSupport::XmlMini.parse(xml)))
-
end
-
-
1
private
-
1
def typecast_xml_value(value)
-
163
case value
-
when Hash
-
146
if value['type'] == 'array'
-
20
_, entries = Array.wrap(value.detect { |k,v| not v.is_a?(String) })
-
6
if entries.nil? || (c = value['__content__'] && c.blank?)
-
2
[]
-
else
-
4
case entries # something weird with classes not matching here. maybe singleton methods breaking is_a?
-
when Array
-
9
entries.collect { |v| typecast_xml_value(v) }
-
when Hash
-
1
[typecast_xml_value(entries)]
-
else
-
raise "can't typecast #{entries.inspect}"
-
end
-
end
-
elsif value['type'] == 'file' ||
-
140
(value['__content__'] && (value.keys.size == 1 || value['__content__'].present?))
-
77
content = value['__content__']
-
77
if parser = ActiveSupport::XmlMini::PARSING[value['type']]
-
48
parser.arity == 1 ? parser.call(content) : parser.call(content, value)
-
else
-
29
content
-
end
-
63
elsif value['type'] == 'string' && value['nil'] != 'true'
-
1
''
-
# blank or nil parsed values are represented by nil
-
62
elsif value.blank? || value['nil'] == 'true'
-
nil
-
# If the type is the only element which makes it then
-
# this still makes the value nil, except if type is
-
# a XML node(where type['value'] is a Hash)
-
55
elsif value['type'] && value.size == 1 && !value['type'].is_a?(::Hash)
-
nil
-
else
-
182
xml_value = Hash[value.map { |k,v| [k, typecast_xml_value(v)] }]
-
-
# Turn { files: { file: #<StringIO> } } into { files: #<StringIO> } so it is compatible with
-
# how multipart uploaded files from HTML appear
-
50
xml_value['file'].is_a?(StringIO) ? xml_value['file'] : xml_value
-
end
-
when Array
-
value.map! { |i| typecast_xml_value(i) }
-
value.length > 1 ? value : value.first
-
when String
-
17
value
-
else
-
raise "can't typecast #{value.class.name} - #{value.inspect}"
-
end
-
end
-
-
1
def unrename_keys(params)
-
315
case params
-
when Hash
-
432
Hash[params.map { |k,v| [k.to_s.tr('-', '_'), unrename_keys(v)] } ]
-
when Array
-
9
params.map { |v| unrename_keys(v) }
-
else
-
166
params
-
end
-
end
-
end
-
end
-
1
class Hash
-
# Returns a new hash with +self+ and +other_hash+ merged recursively.
-
#
-
# h1 = { x: { y: [4,5,6] }, z: [7,8,9] }
-
# h2 = { x: { y: [7,8,9] }, z: 'xyz' }
-
#
-
# h1.deep_merge(h2) #=> {x: {y: [7, 8, 9]}, z: "xyz"}
-
# h2.deep_merge(h1) #=> {x: {y: [4, 5, 6]}, z: [7, 8, 9]}
-
# h1.deep_merge(h2) { |key, old, new| Array.wrap(old) + Array.wrap(new) }
-
# #=> {:x=>{:y=>[4, 5, 6, 7, 8, 9]}, :z=>[7, 8, 9, "xyz"]}
-
1
def deep_merge(other_hash, &block)
-
280
dup.deep_merge!(other_hash, &block)
-
end
-
-
# Same as +deep_merge+, but modifies +self+.
-
1
def deep_merge!(other_hash, &block)
-
315
other_hash.each_pair do |k,v|
-
847
tv = self[k]
-
847
if tv.is_a?(Hash) && v.is_a?(Hash)
-
268
self[k] = tv.deep_merge(v, &block)
-
else
-
579
self[k] = block && tv ? block.call(k, tv, v) : v
-
end
-
end
-
315
self
-
end
-
end
-
1
class Hash
-
# Returns a hash that represents the difference between two hashes.
-
#
-
# {1 => 2}.diff(1 => 2) # => {}
-
# {1 => 2}.diff(1 => 3) # => {1 => 2}
-
# {}.diff(1 => 2) # => {1 => 2}
-
# {1 => 2, 3 => 4}.diff(1 => 2) # => {3 => 4}
-
1
def diff(other)
-
1
ActiveSupport::Deprecation.warn "Hash#diff is no longer used inside of Rails, and is being deprecated with no replacement. If you're using it to compare hashes for the purpose of testing, please use MiniTest's diff instead."
-
1
dup.
-
2
delete_if { |k, v| other[k] == v }.
-
2
merge!(other.dup.delete_if { |k, v| has_key?(k) })
-
end
-
end
-
1
class Hash
-
# Return a hash that includes everything but the given keys. This is useful for
-
# limiting a set of parameters to everything but a few known toggles:
-
#
-
# @person.update_attributes(params[:person].except(:admin))
-
1
def except(*keys)
-
3625
dup.except!(*keys)
-
end
-
-
# Replaces the hash without the given keys.
-
1
def except!(*keys)
-
43454
keys.each { |key| delete(key) }
-
3626
self
-
end
-
end
-
1
require 'active_support/hash_with_indifferent_access'
-
-
1
class Hash
-
-
# Returns an <tt>ActiveSupport::HashWithIndifferentAccess</tt> out of its receiver:
-
#
-
# { a: 1 }.with_indifferent_access['a'] # => 1
-
1
def with_indifferent_access
-
115
ActiveSupport::HashWithIndifferentAccess.new_from_hash_copying_default(self)
-
end
-
-
# Called when object is nested under an object that receives
-
# #with_indifferent_access. This method will be called on the current object
-
# by the enclosing object and is aliased to #with_indifferent_access by
-
# default. Subclasses of Hash may overwrite this method to return +self+ if
-
# converting to an <tt>ActiveSupport::HashWithIndifferentAccess</tt> would not be
-
# desirable.
-
#
-
# b = { b: 1 }
-
# { a: b }.with_indifferent_access['a'] # calls b.nested_under_indifferent_access
-
1
alias nested_under_indifferent_access with_indifferent_access
-
end
-
1
class Hash
-
# Return a new hash with all keys converted using the block operation.
-
#
-
# hash = { name: 'Rob', age: '28' }
-
#
-
# hash.transform_keys{ |key| key.to_s.upcase }
-
# # => { "NAME" => "Rob", "AGE" => "28" }
-
1
def transform_keys
-
1838
result = {}
-
1838
each_key do |key|
-
4425
result[yield(key)] = self[key]
-
end
-
1838
result
-
end
-
-
# Destructively convert all keys using the block operations.
-
# Same as transform_keys but modifies +self+.
-
1
def transform_keys!
-
13
keys.each do |key|
-
25
self[yield(key)] = delete(key)
-
end
-
13
self
-
end
-
-
# Return a new hash with all keys converted to strings.
-
#
-
# hash = { name: 'Rob', age: '28' }
-
#
-
# hash.stringify_keys
-
# #=> { "name" => "Rob", "age" => "28" }
-
1
def stringify_keys
-
88
transform_keys{ |key| key.to_s }
-
end
-
-
# Destructively convert all keys to strings. Same as
-
# +stringify_keys+, but modifies +self+.
-
1
def stringify_keys!
-
12
transform_keys!{ |key| key.to_s }
-
end
-
-
# Return a new hash with all keys converted to symbols, as long as
-
# they respond to +to_sym+.
-
#
-
# hash = { 'name' => 'Rob', 'age' => '28' }
-
#
-
# hash.symbolize_keys
-
# #=> { name: "Rob", age: "28" }
-
1
def symbolize_keys
-
6163
transform_keys{ |key| key.to_sym rescue key }
-
end
-
1
alias_method :to_options, :symbolize_keys
-
-
# Destructively convert all keys to symbols, as long as they respond
-
# to +to_sym+. Same as +symbolize_keys+, but modifies +self+.
-
1
def symbolize_keys!
-
14
transform_keys!{ |key| key.to_sym rescue key }
-
end
-
1
alias_method :to_options!, :symbolize_keys!
-
-
# Validate all keys in a hash match <tt>*valid_keys</tt>, raising ArgumentError
-
# on a mismatch. Note that keys are NOT treated indifferently, meaning if you
-
# use strings for keys but assert symbols as keys, this will fail.
-
#
-
# { name: 'Rob', years: '28' }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key: years"
-
# { name: 'Rob', age: '28' }.assert_valid_keys('name', 'age') # => raises "ArgumentError: Unknown key: name"
-
# { name: 'Rob', age: '28' }.assert_valid_keys(:name, :age) # => passes, raises nothing
-
1
def assert_valid_keys(*valid_keys)
-
37
valid_keys.flatten!
-
37
each_key do |k|
-
25
raise ArgumentError.new("Unknown key: #{k}") unless valid_keys.include?(k)
-
end
-
end
-
-
# Return a new hash with all keys converted by the block operation.
-
# This includes the keys from the root hash and from all
-
# nested hashes.
-
#
-
# hash = { person: { name: 'Rob', age: '28' } }
-
#
-
# hash.deep_transform_keys{ |key| key.to_s.upcase }
-
# # => { "PERSON" => { "NAME" => "Rob", "AGE" => "28" } }
-
1
def deep_transform_keys(&block)
-
391
result = {}
-
391
each do |key, value|
-
1011
result[yield(key)] = value.is_a?(Hash) ? value.deep_transform_keys(&block) : value
-
end
-
391
result
-
end
-
-
# Destructively convert all keys by using the block operation.
-
# This includes the keys from the root hash and from all
-
# nested hashes.
-
1
def deep_transform_keys!(&block)
-
42
keys.each do |key|
-
43
value = delete(key)
-
43
self[yield(key)] = value.is_a?(Hash) ? value.deep_transform_keys!(&block) : value
-
end
-
42
self
-
end
-
-
# Return a new hash with all keys converted to strings.
-
# This includes the keys from the root hash and from all
-
# nested hashes.
-
#
-
# hash = { person: { name: 'Rob', age: '28' } }
-
#
-
# hash.deep_stringify_keys
-
# # => { "person" => { "name" => "Rob", "age" => "28" } }
-
1
def deep_stringify_keys
-
16
deep_transform_keys{ |key| key.to_s }
-
end
-
-
# Destructively convert all keys to strings.
-
# This includes the keys from the root hash and from all
-
# nested hashes.
-
1
def deep_stringify_keys!
-
16
deep_transform_keys!{ |key| key.to_s }
-
end
-
-
# Return a new hash with all keys converted to symbols, as long as
-
# they respond to +to_sym+. This includes the keys from the root hash
-
# and from all nested hashes.
-
#
-
# hash = { 'person' => { 'name' => 'Rob', 'age' => '28' } }
-
#
-
# hash.deep_symbolize_keys
-
# # => { person: { name: "Rob", age: "28" } }
-
1
def deep_symbolize_keys
-
1032
deep_transform_keys{ |key| key.to_sym rescue key }
-
end
-
-
# Destructively convert all keys to symbols, as long as they respond
-
# to +to_sym+. This includes the keys from the root hash and from all
-
# nested hashes.
-
1
def deep_symbolize_keys!
-
26
deep_transform_keys!{ |key| key.to_sym rescue key }
-
end
-
end
-
1
class Hash
-
# Merges the caller into +other_hash+. For example,
-
#
-
# options = options.reverse_merge(size: 25, velocity: 10)
-
#
-
# is equivalent to
-
#
-
# options = { size: 25, velocity: 10 }.merge(options)
-
#
-
# This is particularly useful for initializing an options hash
-
# with default values.
-
1
def reverse_merge(other_hash)
-
2
other_hash.merge(self)
-
end
-
-
# Destructive +reverse_merge+.
-
1
def reverse_merge!(other_hash)
-
# right wins if there is no left
-
6
merge!( other_hash ){|key,left,right| left }
-
end
-
1
alias_method :reverse_update, :reverse_merge!
-
end
-
1
class Hash
-
# Slice a hash to include only the given keys. This is useful for
-
# limiting an options hash to valid keys before passing to a method:
-
#
-
# def search(criteria = {})
-
# criteria.assert_valid_keys(:mass, :velocity, :time)
-
# end
-
#
-
# search(options.slice(:mass, :velocity, :time))
-
#
-
# If you have an array of keys you want to limit to, you should splat them:
-
#
-
# valid_keys = [:mass, :velocity, :time]
-
# search(options.slice(*valid_keys))
-
1
def slice(*keys)
-
47
keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
-
101
keys.each_with_object(self.class.new) { |k, hash| hash[k] = self[k] if has_key?(k) }
-
end
-
-
# Replaces the hash with only the given keys.
-
# Returns a hash containing the removed key/value pairs.
-
#
-
# { a: 1, b: 2, c: 3, d: 4 }.slice!(:a, :b)
-
# # => {:c=>3, :d=>4}
-
1
def slice!(*keys)
-
8
keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
-
4
omit = slice(*self.keys - keys)
-
4
hash = slice(*keys)
-
4
replace(hash)
-
4
omit
-
end
-
-
# Removes and returns the key/value pairs matching the given keys.
-
#
-
# { a: 1, b: 2, c: 3, d: 4 }.extract!(:a, :b) # => {:a=>1, :b=>2}
-
# { a: 1, b: 2 }.extract!(:a, :x) # => {:a=>1}
-
1
def extract!(*keys)
-
13
keys.each_with_object(self.class.new) { |key, result| result[key] = delete(key) if has_key?(key) }
-
end
-
end
-
1
require 'active_support/core_ext/integer/multiple'
-
1
require 'active_support/core_ext/integer/inflections'
-
1
require 'active_support/core_ext/integer/time'
-
1
require 'active_support/inflector'
-
-
1
class Integer
-
# Ordinalize turns a number into an ordinal string used to denote the
-
# position in an ordered sequence such as 1st, 2nd, 3rd, 4th.
-
#
-
# 1.ordinalize # => "1st"
-
# 2.ordinalize # => "2nd"
-
# 1002.ordinalize # => "1002nd"
-
# 1003.ordinalize # => "1003rd"
-
# -11.ordinalize # => "-11th"
-
# -1001.ordinalize # => "-1001st"
-
1
def ordinalize
-
2
ActiveSupport::Inflector.ordinalize(self)
-
end
-
-
# Ordinal returns the suffix used to denote the position
-
# in an ordered sequence such as 1st, 2nd, 3rd, 4th.
-
#
-
# 1.ordinal # => "st"
-
# 2.ordinal # => "nd"
-
# 1002.ordinal # => "nd"
-
# 1003.ordinal # => "rd"
-
# -11.ordinal # => "th"
-
# -1001.ordinal # => "st"
-
1
def ordinal
-
2
ActiveSupport::Inflector.ordinal(self)
-
end
-
end
-
1
class Integer
-
# Check whether the integer is evenly divisible by the argument.
-
#
-
# 0.multiple_of?(0) #=> true
-
# 6.multiple_of?(5) #=> false
-
# 10.multiple_of?(2) #=> true
-
1
def multiple_of?(number)
-
13
number != 0 ? self % number == 0 : zero?
-
end
-
end
-
1
class Integer
-
# Enables the use of time calculations and declarations, like <tt>45.minutes +
-
# 2.hours + 4.years</tt>.
-
#
-
# These methods use Time#advance for precise date calculations when using
-
# <tt>from_now</tt>, +ago+, etc. as well as adding or subtracting their
-
# results from a Time object.
-
#
-
# # equivalent to Time.now.advance(months: 1)
-
# 1.month.from_now
-
#
-
# # equivalent to Time.now.advance(years: 2)
-
# 2.years.from_now
-
#
-
# # equivalent to Time.now.advance(months: 4, years: 5)
-
# (4.months + 5.years).from_now
-
#
-
# While these methods provide precise calculation when used as in the examples
-
# above, care should be taken to note that this is not true if the result of
-
# +months+, +years+, etc is converted before use:
-
#
-
# # equivalent to 30.days.to_i.from_now
-
# 1.month.to_i.from_now
-
#
-
# # equivalent to 365.25.days.to_f.from_now
-
# 1.year.to_f.from_now
-
#
-
# In such cases, Ruby's core
-
# Date[http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and
-
# Time[http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html] should be used for precision
-
# date and time arithmetic.
-
1
def months
-
46
ActiveSupport::Duration.new(self * 30.days, [[:months, self]])
-
end
-
1
alias :month :months
-
-
1
def years
-
29
ActiveSupport::Duration.new(self * 365.25.days, [[:years, self]])
-
end
-
1
alias :year :years
-
end
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/core_ext/kernel/agnostics'
-
1
require 'active_support/core_ext/kernel/debugger'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
class Object
-
# Makes backticks behave (somewhat more) similarly on all platforms.
-
# On win32 `nonexistent_command` raises Errno::ENOENT; on Unix, the
-
# spawned shell prints a message to stderr and sets $?. We emulate
-
# Unix on the former but not the latter.
-
1
def `(command) #:nodoc:
-
super
-
rescue Errno::ENOENT => e
-
STDERR.puts "#$0: #{e}"
-
end
-
end
-
1
module Kernel
-
1
unless respond_to?(:debugger)
-
# Starts a debugging session if the +debugger+ gem has been loaded (call rails server --debugger to do load it).
-
1
def debugger
-
2
message = "\n***** Debugger requested, but was not available (ensure the debugger gem is listed in Gemfile/installed as gem): Start server with --debugger to enable *****\n"
-
2
defined?(Rails) ? Rails.logger.info(message) : $stderr.puts(message)
-
end
-
1
alias breakpoint debugger unless respond_to?(:breakpoint)
-
end
-
end
-
1
module Kernel
-
# class_eval on an object acts like singleton_class.class_eval.
-
1
def class_eval(*args, &block)
-
3
singleton_class.class_eval(*args, &block)
-
end
-
end
-
1
class LoadError
-
1
REGEXPS = [
-
/^no such file to load -- (.+)$/i,
-
/^Missing \w+ (?:file\s*)?([^\s]+.rb)$/i,
-
/^Missing API definition file in (.+)$/i,
-
/^cannot load such file -- (.+)$/i,
-
]
-
-
1
unless method_defined?(:path)
-
1
def path
-
@path ||= begin
-
2
REGEXPS.find do |regex|
-
8
message =~ regex
-
end
-
2
$1
-
2
end
-
end
-
end
-
-
1
def is_missing?(location)
-
location.sub(/\.rb$/, '') == path.sub(/\.rb$/, '')
-
end
-
end
-
-
1
MissingSourceFile = LoadError
-
1
require 'active_support/core_ext/module/aliasing'
-
1
require 'active_support/core_ext/module/introspection'
-
1
require 'active_support/core_ext/module/anonymous'
-
1
require 'active_support/core_ext/module/reachable'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/module/attr_internal'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'active_support/core_ext/module/deprecation'
-
1
require 'active_support/core_ext/module/remove_method'
-
1
require 'active_support/core_ext/module/qualified_const'
-
1
class Module
-
# Encapsulates the common pattern of:
-
#
-
# alias_method :foo_without_feature, :foo
-
# alias_method :foo, :foo_with_feature
-
#
-
# With this, you simply do:
-
#
-
# alias_method_chain :foo, :feature
-
#
-
# And both aliases are set up for you.
-
#
-
# Query and bang methods (foo?, foo!) keep the same punctuation:
-
#
-
# alias_method_chain :foo?, :feature
-
#
-
# is equivalent to
-
#
-
# alias_method :foo_without_feature?, :foo?
-
# alias_method :foo?, :foo_with_feature?
-
#
-
# so you can safely chain foo, foo?, and foo! with the same feature.
-
1
def alias_method_chain(target, feature)
-
# Strip out punctuation on predicates or bang methods since
-
# e.g. target?_without_feature is not a valid method name.
-
34
aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1
-
34
yield(aliased_target, punctuation) if block_given?
-
-
34
with_method = "#{aliased_target}_with_#{feature}#{punctuation}"
-
34
without_method = "#{aliased_target}_without_#{feature}#{punctuation}"
-
-
34
alias_method without_method, target
-
34
alias_method target, with_method
-
-
case
-
when public_method_defined?(without_method)
-
30
public target
-
when protected_method_defined?(without_method)
-
1
protected target
-
when private_method_defined?(without_method)
-
2
private target
-
33
end
-
end
-
-
# Allows you to make aliases for attributes, which includes
-
# getter, setter, and query methods.
-
#
-
# class Content < ActiveRecord::Base
-
# # has a title attribute
-
# end
-
#
-
# class Email < Content
-
# alias_attribute :subject, :title
-
# end
-
#
-
# e = Email.find(1)
-
# e.title # => "Superstars"
-
# e.subject # => "Superstars"
-
# e.subject? # => true
-
# e.subject = "Megastars"
-
# e.title # => "Megastars"
-
1
def alias_attribute(new_name, old_name)
-
2
module_eval <<-STR, __FILE__, __LINE__ + 1
-
def #{new_name}; self.#{old_name}; end # def subject; self.title; end
-
def #{new_name}?; self.#{old_name}?; end # def subject?; self.title?; end
-
def #{new_name}=(v); self.#{old_name} = v; end # def subject=(v); self.title = v; end
-
STR
-
end
-
end
-
1
class Module
-
# A module may or may not have a name.
-
#
-
# module M; end
-
# M.name # => "M"
-
#
-
# m = Module.new
-
# m.name # => nil
-
#
-
# A module gets a name when it is first assigned to a constant. Either
-
# via the +module+ or +class+ keyword or by an explicit assignment:
-
#
-
# m = Module.new # creates an anonymous module
-
# M = m # => m gets a name here as a side-effect
-
# m.name # => "M"
-
1
def anonymous?
-
1207
name.nil?
-
end
-
end
-
1
class Module
-
# Declares an attribute reader backed by an internally-named instance variable.
-
1
def attr_internal_reader(*attrs)
-
6
attrs.each {|attr_name| attr_internal_define(attr_name, :reader)}
-
end
-
-
# Declares an attribute writer backed by an internally-named instance variable.
-
1
def attr_internal_writer(*attrs)
-
6
attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}
-
end
-
-
# Declares an attribute reader and writer backed by an internally-named instance
-
# variable.
-
1
def attr_internal_accessor(*attrs)
-
2
attr_internal_reader(*attrs)
-
2
attr_internal_writer(*attrs)
-
end
-
1
alias_method :attr_internal, :attr_internal_accessor
-
-
2
class << self; attr_accessor :attr_internal_naming_format end
-
1
self.attr_internal_naming_format = '@_%s'
-
-
1
private
-
1
def attr_internal_ivar_name(attr)
-
6
Module.attr_internal_naming_format % attr
-
end
-
-
1
def attr_internal_define(attr_name, type)
-
6
internal_name = attr_internal_ivar_name(attr_name).sub(/\A@/, '')
-
6
class_eval do # class_eval is necessary on 1.9 or else the methods a made private
-
# use native attr_* methods as they are faster on some Ruby implementations
-
6
send("attr_#{type}", internal_name)
-
end
-
6
attr_name, internal_name = "#{attr_name}=", "#{internal_name}=" if type == :writer
-
6
alias_method attr_name, internal_name
-
6
remove_method internal_name
-
end
-
end
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
class Module
-
1
def mattr_reader(*syms)
-
47
options = syms.extract_options!
-
47
syms.each do |sym|
-
47
raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\w*$/
-
46
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
@@#{sym} = nil unless defined? @@#{sym}
-
-
def self.#{sym}
-
@@#{sym}
-
end
-
EOS
-
-
46
unless options[:instance_reader] == false || options[:instance_accessor] == false
-
33
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
def #{sym}
-
@@#{sym}
-
end
-
EOS
-
end
-
end
-
end
-
-
1
def mattr_writer(*syms)
-
41
options = syms.extract_options!
-
41
syms.each do |sym|
-
41
raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\w*$/
-
40
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
def self.#{sym}=(obj)
-
@@#{sym} = obj
-
end
-
EOS
-
-
40
unless options[:instance_writer] == false || options[:instance_accessor] == false
-
20
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
def #{sym}=(obj)
-
@@#{sym} = obj
-
end
-
EOS
-
end
-
end
-
end
-
-
# Extends the module object with module and instance accessors for class attributes,
-
# just like the native attr* accessors for instance attributes.
-
#
-
# module AppConfiguration
-
# mattr_accessor :google_api_key
-
#
-
# self.google_api_key = "123456789"
-
# end
-
#
-
# AppConfiguration.google_api_key # => "123456789"
-
# AppConfiguration.google_api_key = "overriding the api key!"
-
# AppConfiguration.google_api_key # => "overriding the api key!"
-
#
-
# To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
-
# To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
-
# To opt out of both instance methods, pass <tt>instance_accessor: false</tt>.
-
1
def mattr_accessor(*syms)
-
40
mattr_reader(*syms)
-
40
mattr_writer(*syms)
-
end
-
end
-
1
class Module
-
# Provides a delegate class method to easily expose contained objects' public methods
-
# as your own. Pass one or more methods (specified as symbols or strings)
-
# and the name of the target object via the <tt>:to</tt> option (also a symbol
-
# or string). At least one method and the <tt>:to</tt> option are required.
-
#
-
# Delegation is particularly useful with Active Record associations:
-
#
-
# class Greeter < ActiveRecord::Base
-
# def hello
-
# 'hello'
-
# end
-
#
-
# def goodbye
-
# 'goodbye'
-
# end
-
# end
-
#
-
# class Foo < ActiveRecord::Base
-
# belongs_to :greeter
-
# delegate :hello, to: :greeter
-
# end
-
#
-
# Foo.new.hello # => "hello"
-
# Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for #<Foo:0x1af30c>
-
#
-
# Multiple delegates to the same target are allowed:
-
#
-
# class Foo < ActiveRecord::Base
-
# belongs_to :greeter
-
# delegate :hello, :goodbye, to: :greeter
-
# end
-
#
-
# Foo.new.goodbye # => "goodbye"
-
#
-
# Methods can be delegated to instance variables, class variables, or constants
-
# by providing them as a symbols:
-
#
-
# class Foo
-
# CONSTANT_ARRAY = [0,1,2,3]
-
# @@class_array = [4,5,6,7]
-
#
-
# def initialize
-
# @instance_array = [8,9,10,11]
-
# end
-
# delegate :sum, to: :CONSTANT_ARRAY
-
# delegate :min, to: :@@class_array
-
# delegate :max, to: :@instance_array
-
# end
-
#
-
# Foo.new.sum # => 6
-
# Foo.new.min # => 4
-
# Foo.new.max # => 11
-
#
-
# It's also possible to delegate a method to the class by using +:class+:
-
#
-
# class Foo
-
# def self.hello
-
# "world"
-
# end
-
#
-
# delegate :hello, to: :class
-
# end
-
#
-
# Foo.new.hello # => "world"
-
#
-
# Delegates can optionally be prefixed using the <tt>:prefix</tt> option. If the value
-
# is <tt>true</tt>, the delegate methods are prefixed with the name of the object being
-
# delegated to.
-
#
-
# Person = Struct.new(:name, :address)
-
#
-
# class Invoice < Struct.new(:client)
-
# delegate :name, :address, to: :client, prefix: true
-
# end
-
#
-
# john_doe = Person.new('John Doe', 'Vimmersvej 13')
-
# invoice = Invoice.new(john_doe)
-
# invoice.client_name # => "John Doe"
-
# invoice.client_address # => "Vimmersvej 13"
-
#
-
# It is also possible to supply a custom prefix.
-
#
-
# class Invoice < Struct.new(:client)
-
# delegate :name, :address, to: :client, prefix: :customer
-
# end
-
#
-
# invoice = Invoice.new(john_doe)
-
# invoice.customer_name # => 'John Doe'
-
# invoice.customer_address # => 'Vimmersvej 13'
-
#
-
# If the delegate object is +nil+ an exception is raised, and that happens
-
# no matter whether +nil+ responds to the delegated method. You can get a
-
# +nil+ instead with the +:allow_nil+ option.
-
#
-
# class Foo
-
# attr_accessor :bar
-
# def initialize(bar = nil)
-
# @bar = bar
-
# end
-
# delegate :zoo, to: :bar
-
# end
-
#
-
# Foo.new.zoo # raises NoMethodError exception (you called nil.zoo)
-
#
-
# class Foo
-
# attr_accessor :bar
-
# def initialize(bar = nil)
-
# @bar = bar
-
# end
-
# delegate :zoo, to: :bar, allow_nil: true
-
# end
-
#
-
# Foo.new.zoo # returns nil
-
1
def delegate(*methods)
-
58
options = methods.pop
-
58
unless options.is_a?(Hash) && to = options[:to]
-
2
raise ArgumentError, 'Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, to: :greeter).'
-
end
-
-
56
prefix, allow_nil = options.values_at(:prefix, :allow_nil)
-
-
56
if prefix == true && to =~ /^[^a-z_]/
-
1
raise ArgumentError, 'Can only automatically set the delegation prefix when delegating to a method.'
-
end
-
-
55
method_prefix = \
-
if prefix
-
5
"#{prefix == true ? to : prefix}_"
-
else
-
50
''
-
end
-
-
55
file, line = caller.first.split(':', 2)
-
55
line = line.to_i
-
-
55
to = to.to_s
-
55
to = 'self.class' if to == 'class'
-
-
55
methods.each do |method|
-
# Attribute writer methods only accept one argument. Makes sure []=
-
# methods still accept two arguments.
-
156
definition = (method =~ /[^\]]=$/) ? 'arg' : '*args, &block'
-
-
156
if allow_nil
-
4
module_eval(<<-EOS, file, line - 2)
-
def #{method_prefix}#{method}(#{definition}) # def customer_name(*args, &block)
-
if #{to} || #{to}.respond_to?(:#{method}) # if client || client.respond_to?(:name)
-
#{to}.#{method}(#{definition}) # client.name(*args, &block)
-
end # end
-
end # end
-
EOS
-
else
-
152
exception = %(raise "#{self}##{method_prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}")
-
-
152
module_eval(<<-EOS, file, line - 1)
-
def #{method_prefix}#{method}(#{definition}) # def customer_name(*args, &block)
-
#{to}.#{method}(#{definition}) # client.name(*args, &block)
-
rescue NoMethodError # rescue NoMethodError
-
if #{to}.nil? # if client.nil?
-
#{exception} # # add helpful message to the exception
-
else # else
-
raise # raise
-
end # end
-
end # end
-
EOS
-
end
-
end
-
end
-
end
-
1
require 'active_support/deprecation/method_wrappers'
-
-
1
class Module
-
# deprecate :foo
-
# deprecate bar: 'message'
-
# deprecate :foo, :bar, baz: 'warning!', qux: 'gone!'
-
#
-
# You can also use custom deprecator instance:
-
#
-
# deprecate :foo, deprecator: MyLib::Deprecator.new
-
# deprecate :foo, bar: "warning!", deprecator: MyLib::Deprecator.new
-
#
-
# \Custom deprecators must respond to <tt>deprecation_warning(deprecated_method_name, message, caller_backtrace)</tt>
-
# method where you can implement your custom warning behavior.
-
#
-
# class MyLib::Deprecator
-
# def deprecation_warning(deprecated_method_name, message, caller_backtrace)
-
# message = "#{method_name} is deprecated and will be removed from MyLibrary | #{message}"
-
# Kernel.warn message
-
# end
-
# end
-
1
def deprecate(*method_names)
-
6
ActiveSupport::Deprecation.deprecate_methods(self, *method_names)
-
end
-
end
-
1
require 'active_support/inflector'
-
-
1
class Module
-
# Returns the name of the module containing this one.
-
#
-
# M::N.parent_name # => "M"
-
1
def parent_name
-
236
if defined? @parent_name
-
212
@parent_name
-
else
-
24
@parent_name = name =~ /::[^:]+\Z/ ? $`.freeze : nil
-
end
-
end
-
-
# Returns the module which contains this one according to its name.
-
#
-
# module M
-
# module N
-
# end
-
# end
-
# X = M::N
-
#
-
# M::N.parent # => M
-
# X.parent # => M
-
#
-
# The parent of top-level and anonymous modules is Object.
-
#
-
# M.parent # => Object
-
# Module.new.parent # => Object
-
1
def parent
-
129
parent_name ? ActiveSupport::Inflector.constantize(parent_name) : Object
-
end
-
-
# Returns all the parents of this module according to its name, ordered from
-
# nested outwards. The receiver is not contained within the result.
-
#
-
# module M
-
# module N
-
# end
-
# end
-
# X = M::N
-
#
-
# M.parents # => [Object]
-
# M::N.parents # => [M, Object]
-
# X.parents # => [M, Object]
-
1
def parents
-
69
parents = []
-
69
if parent_name
-
19
parts = parent_name.split('::')
-
19
until parts.empty?
-
21
parents << ActiveSupport::Inflector.constantize(parts * '::')
-
21
parts.pop
-
end
-
end
-
69
parents << Object unless parents.include? Object
-
69
parents
-
end
-
-
1
def local_constants #:nodoc:
-
150
constants(false)
-
end
-
-
# *DEPRECATED*: Use +local_constants+ instead.
-
#
-
# Returns the names of the constants defined locally as strings.
-
#
-
# module M
-
# X = 1
-
# end
-
# M.local_constant_names # => ["X"]
-
#
-
# This method is useful for forward compatibility, since Ruby 1.8 returns
-
# constant names as strings, whereas 1.9 returns them as symbols.
-
1
def local_constant_names
-
1
ActiveSupport::Deprecation.warn 'Module#local_constant_names is deprecated, use Module#local_constants instead'
-
3
local_constants.map { |c| c.to_s }
-
end
-
end
-
1
require 'active_support/core_ext/string/inflections'
-
-
#--
-
# Allows code reuse in the methods below without polluting Module.
-
#++
-
1
module QualifiedConstUtils
-
1
def self.raise_if_absolute(path)
-
1453
raise NameError.new("wrong constant name #$&") if path =~ /\A::[^:]+/
-
end
-
-
1
def self.names(path)
-
1442
path.split('::')
-
end
-
end
-
-
##
-
# Extends the API for constants to be able to deal with qualified names. Arguments
-
# are assumed to be relative to the receiver.
-
#
-
#--
-
# Qualified names are required to be relative because we are extending existing
-
# methods that expect constant names, ie, relative paths of length 1. For example,
-
# Object.const_get('::String') raises NameError and so does qualified_const_get.
-
#++
-
1
class Module
-
1
def qualified_const_defined?(path, search_parents=true)
-
1436
QualifiedConstUtils.raise_if_absolute(path)
-
-
1434
QualifiedConstUtils.names(path).inject(self) do |mod, name|
-
1775
return unless mod.const_defined?(name, search_parents)
-
1722
mod.const_get(name)
-
end
-
1381
return true
-
end
-
-
1
def qualified_const_get(path)
-
10
QualifiedConstUtils.raise_if_absolute(path)
-
-
8
QualifiedConstUtils.names(path).inject(self) do |mod, name|
-
15
mod.const_get(name)
-
end
-
end
-
-
1
def qualified_const_set(path, value)
-
7
QualifiedConstUtils.raise_if_absolute(path)
-
-
5
const_name = path.demodulize
-
5
mod_name = path.deconstantize
-
5
mod = mod_name.empty? ? self : qualified_const_get(mod_name)
-
5
mod.const_set(const_name, value)
-
end
-
end
-
1
require 'active_support/core_ext/module/anonymous'
-
1
require 'active_support/core_ext/string/inflections'
-
-
1
class Module
-
1
def reachable? #:nodoc:
-
10
!anonymous? && name.safe_constantize.equal?(self)
-
end
-
end
-
1
class Module
-
1
def remove_possible_method(method)
-
259
if method_defined?(method) || private_method_defined?(method)
-
188
undef_method(method)
-
end
-
end
-
-
1
def redefine_method(method, &block)
-
1
remove_possible_method(method)
-
1
define_method(method, &block)
-
end
-
end
-
1
class NameError
-
# Extract the name of the missing constant from the exception message.
-
1
def missing_name
-
27
if /undefined local variable or method/ !~ message
-
25
$1 if /((::)?([A-Z]\w*)(::[A-Z]\w*)*)$/ =~ message
-
end
-
end
-
-
# Was this exception raised because the given name was missing?
-
1
def missing_name?(name)
-
25
if name.is_a? Symbol
-
2
last_name = (missing_name || '').split('::').last
-
2
last_name == name.to_s
-
else
-
23
missing_name == name.to_s
-
end
-
end
-
end
-
1
require 'active_support/core_ext/numeric/bytes'
-
1
require 'active_support/core_ext/numeric/time'
-
1
require 'active_support/core_ext/numeric/conversions'
-
1
class Numeric
-
1
KILOBYTE = 1024
-
1
MEGABYTE = KILOBYTE * 1024
-
1
GIGABYTE = MEGABYTE * 1024
-
1
TERABYTE = GIGABYTE * 1024
-
1
PETABYTE = TERABYTE * 1024
-
1
EXABYTE = PETABYTE * 1024
-
-
# Enables the use of byte calculations and declarations, like 45.bytes + 2.6.megabytes
-
1
def bytes
-
1
self
-
end
-
1
alias :byte :bytes
-
-
1
def kilobytes
-
10
self * KILOBYTE
-
end
-
1
alias :kilobyte :kilobytes
-
-
1
def megabytes
-
16
self * MEGABYTE
-
end
-
1
alias :megabyte :megabytes
-
-
1
def gigabytes
-
6
self * GIGABYTE
-
end
-
1
alias :gigabyte :gigabytes
-
-
1
def terabytes
-
3
self * TERABYTE
-
end
-
1
alias :terabyte :terabytes
-
-
1
def petabytes
-
3
self * PETABYTE
-
end
-
1
alias :petabyte :petabytes
-
-
1
def exabytes
-
3
self * EXABYTE
-
end
-
1
alias :exabyte :exabytes
-
end
-
1
require 'active_support/core_ext/big_decimal/conversions'
-
1
require 'active_support/number_helper'
-
-
1
class Numeric
-
-
# Provides options for converting numbers into formatted strings.
-
# Options are provided for phone numbers, currency, percentage,
-
# precision, positional notation, file size and pretty printing.
-
#
-
# ==== Options
-
#
-
# For details on which formats use which options, see ActiveSupport::NumberHelper
-
#
-
# ==== Examples
-
#
-
# Phone Numbers:
-
# 5551234.to_s(:phone) # => 555-1234
-
# 1235551234.to_s(:phone) # => 123-555-1234
-
# 1235551234.to_s(:phone, area_code: true) # => (123) 555-1234
-
# 1235551234.to_s(:phone, delimiter: ' ') # => 123 555 1234
-
# 1235551234.to_s(:phone, area_code: true, extension: 555) # => (123) 555-1234 x 555
-
# 1235551234.to_s(:phone, country_code: 1) # => +1-123-555-1234
-
# 1235551234.to_s(:phone, country_code: 1, extension: 1343, delimiter: '.')
-
# # => +1.123.555.1234 x 1343
-
#
-
# Currency:
-
# 1234567890.50.to_s(:currency) # => $1,234,567,890.50
-
# 1234567890.506.to_s(:currency) # => $1,234,567,890.51
-
# 1234567890.506.to_s(:currency, precision: 3) # => $1,234,567,890.506
-
# 1234567890.506.to_s(:currency, locale: :fr) # => 1 234 567 890,51 €
-
# -1234567890.50.to_s(:currency, negative_format: '(%u%n)')
-
# # => ($1,234,567,890.50)
-
# 1234567890.50.to_s(:currency, unit: '£', separator: ',', delimiter: '')
-
# # => £1234567890,50
-
# 1234567890.50.to_s(:currency, unit: '£', separator: ',', delimiter: '', format: '%n %u')
-
# # => 1234567890,50 £
-
#
-
# Percentage:
-
# 100.to_s(:percentage) # => 100.000%
-
# 100.to_s(:percentage, precision: 0) # => 100%
-
# 1000.to_s(:percentage, delimiter: '.', separator: ',') # => 1.000,000%
-
# 302.24398923423.to_s(:percentage, precision: 5) # => 302.24399%
-
# 1000.to_s(:percentage, locale: :fr) # => 1 000,000%
-
# 100.to_s(:percentage, format: '%n %') # => 100 %
-
#
-
# Delimited:
-
# 12345678.to_s(:delimited) # => 12,345,678
-
# 12345678.05.to_s(:delimited) # => 12,345,678.05
-
# 12345678.to_s(:delimited, delimiter: '.') # => 12.345.678
-
# 12345678.to_s(:delimited, delimiter: ',') # => 12,345,678
-
# 12345678.05.to_s(:delimited, separator: ' ') # => 12,345,678 05
-
# 12345678.05.to_s(:delimited, locale: :fr) # => 12 345 678,05
-
# 98765432.98.to_s(:delimited, delimiter: ' ', separator: ',')
-
# # => 98 765 432,98
-
#
-
# Rounded:
-
# 111.2345.to_s(:rounded) # => 111.235
-
# 111.2345.to_s(:rounded, precision: 2) # => 111.23
-
# 13.to_s(:rounded, precision: 5) # => 13.00000
-
# 389.32314.to_s(:rounded, precision: 0) # => 389
-
# 111.2345.to_s(:rounded, significant: true) # => 111
-
# 111.2345.to_s(:rounded, precision: 1, significant: true) # => 100
-
# 13.to_s(:rounded, precision: 5, significant: true) # => 13.000
-
# 111.234.to_s(:rounded, locale: :fr) # => 111,234
-
# 13.to_s(:rounded, precision: 5, significant: true, strip_insignificant_zeros: true)
-
# # => 13
-
# 389.32314.to_s(:rounded, precision: 4, significant: true) # => 389.3
-
# 1111.2345.to_s(:rounded, precision: 2, separator: ',', delimiter: '.')
-
# # => 1.111,23
-
#
-
# Human-friendly size in Bytes:
-
# 123.to_s(:human_size) # => 123 Bytes
-
# 1234.to_s(:human_size) # => 1.21 KB
-
# 12345.to_s(:human_size) # => 12.1 KB
-
# 1234567.to_s(:human_size) # => 1.18 MB
-
# 1234567890.to_s(:human_size) # => 1.15 GB
-
# 1234567890123.to_s(:human_size) # => 1.12 TB
-
# 1234567.to_s(:human_size, precision: 2) # => 1.2 MB
-
# 483989.to_s(:human_size, precision: 2) # => 470 KB
-
# 1234567.to_s(:human_size, precision: 2, separator: ',') # => 1,2 MB
-
# 1234567890123.to_s(:human_size, precision: 5) # => "1.1229 TB"
-
# 524288000.to_s(:human_size, precision: 5) # => "500 MB"
-
#
-
# Human-friendly format:
-
# 123.to_s(:human) # => "123"
-
# 1234.to_s(:human) # => "1.23 Thousand"
-
# 12345.to_s(:human) # => "12.3 Thousand"
-
# 1234567.to_s(:human) # => "1.23 Million"
-
# 1234567890.to_s(:human) # => "1.23 Billion"
-
# 1234567890123.to_s(:human) # => "1.23 Trillion"
-
# 1234567890123456.to_s(:human) # => "1.23 Quadrillion"
-
# 1234567890123456789.to_s(:human) # => "1230 Quadrillion"
-
# 489939.to_s(:human, precision: 2) # => "490 Thousand"
-
# 489939.to_s(:human, precision: 4) # => "489.9 Thousand"
-
# 1234567.to_s(:human, precision: 4,
-
# significant: false) # => "1.2346 Million"
-
# 1234567.to_s(:human, precision: 1,
-
# separator: ',',
-
# significant: false) # => "1,2 Million"
-
1
def to_formatted_s(format = :default, options = {})
-
167
case format
-
when :phone
-
11
return ActiveSupport::NumberHelper.number_to_phone(self, options)
-
when :currency
-
8
return ActiveSupport::NumberHelper.number_to_currency(self, options)
-
when :percentage
-
6
return ActiveSupport::NumberHelper.number_to_percentage(self, options)
-
when :delimited
-
13
return ActiveSupport::NumberHelper.number_to_delimited(self, options)
-
when :rounded
-
40
return ActiveSupport::NumberHelper.number_to_rounded(self, options)
-
when :human
-
44
return ActiveSupport::NumberHelper.number_to_human(self, options)
-
when :human_size
-
45
return ActiveSupport::NumberHelper.number_to_human_size(self, options)
-
else
-
self.to_default_s
-
end
-
end
-
-
1
[Float, Fixnum, Bignum, BigDecimal].each do |klass|
-
4
klass.send(:alias_method, :to_default_s, :to_s)
-
-
4
klass.send(:define_method, :to_s) do |*args|
-
10107
if args[0].is_a?(Symbol)
-
167
format = args[0]
-
167
options = args[1] || {}
-
-
167
self.to_formatted_s(format, options)
-
else
-
9940
to_default_s(*args)
-
end
-
end
-
end
-
end
-
1
require 'active_support/duration'
-
1
require 'active_support/core_ext/time/calculations'
-
1
require 'active_support/core_ext/time/acts_like'
-
-
1
class Numeric
-
# Enables the use of time calculations and declarations, like 45.minutes + 2.hours + 4.years.
-
#
-
# These methods use Time#advance for precise date calculations when using from_now, ago, etc.
-
# as well as adding or subtracting their results from a Time object. For example:
-
#
-
# # equivalent to Time.current.advance(months: 1)
-
# 1.month.from_now
-
#
-
# # equivalent to Time.current.advance(years: 2)
-
# 2.years.from_now
-
#
-
# # equivalent to Time.current.advance(months: 4, years: 5)
-
# (4.months + 5.years).from_now
-
#
-
# While these methods provide precise calculation when used as in the examples above, care
-
# should be taken to note that this is not true if the result of `months', `years', etc is
-
# converted before use:
-
#
-
# # equivalent to 30.days.to_i.from_now
-
# 1.month.to_i.from_now
-
#
-
# # equivalent to 365.25.days.to_f.from_now
-
# 1.year.to_f.from_now
-
#
-
# In such cases, Ruby's core
-
# Date[http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and
-
# Time[http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html] should be used for precision
-
# date and time arithmetic.
-
1
def seconds
-
57
ActiveSupport::Duration.new(self, [[:seconds, self]])
-
end
-
1
alias :second :seconds
-
-
1
def minutes
-
102
ActiveSupport::Duration.new(self * 60, [[:seconds, self * 60]])
-
end
-
1
alias :minute :minutes
-
-
1
def hours
-
249
ActiveSupport::Duration.new(self * 3600, [[:seconds, self * 3600]])
-
end
-
1
alias :hour :hours
-
-
1
def days
-
175
ActiveSupport::Duration.new(self * 24.hours, [[:days, self]])
-
end
-
1
alias :day :days
-
-
1
def weeks
-
21
ActiveSupport::Duration.new(self * 7.days, [[:days, self * 7]])
-
end
-
1
alias :week :weeks
-
-
1
def fortnights
-
12
ActiveSupport::Duration.new(self * 2.weeks, [[:days, self * 14]])
-
end
-
1
alias :fortnight :fortnights
-
-
# Reads best without arguments: 10.minutes.ago
-
1
def ago(time = ::Time.current)
-
15
time - self
-
end
-
-
# Reads best with argument: 10.minutes.until(time)
-
1
alias :until :ago
-
-
# Reads best with argument: 10.minutes.since(time)
-
1
def since(time = ::Time.current)
-
23
time + self
-
end
-
-
# Reads best without arguments: 10.minutes.from_now
-
1
alias :from_now :since
-
end
-
1
require 'active_support/core_ext/object/acts_like'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/core_ext/object/duplicable'
-
1
require 'active_support/core_ext/object/deep_dup'
-
1
require 'active_support/core_ext/object/try'
-
1
require 'active_support/core_ext/object/inclusion'
-
-
1
require 'active_support/core_ext/object/conversions'
-
1
require 'active_support/core_ext/object/instance_variables'
-
-
1
require 'active_support/core_ext/object/to_json'
-
1
require 'active_support/core_ext/object/to_param'
-
1
require 'active_support/core_ext/object/to_query'
-
1
require 'active_support/core_ext/object/with_options'
-
1
class Object
-
# A duck-type assistant method. For example, Active Support extends Date
-
# to define an acts_like_date? method, and extends Time to define
-
# acts_like_time?. As a result, we can do "x.acts_like?(:time)" and
-
# "x.acts_like?(:date)" to do duck-type-safe comparisons, since classes that
-
# we want to act like Time simply need to define an acts_like_time? method.
-
1
def acts_like?(duck)
-
683
respond_to? :"acts_like_#{duck}?"
-
end
-
end
-
# encoding: utf-8
-
-
1
class Object
-
# An object is blank if it's false, empty, or a whitespace string.
-
# For example, '', ' ', +nil+, [], and {} are all blank.
-
#
-
# This simplifies:
-
#
-
# if address.nil? || address.empty?
-
#
-
# ...to:
-
#
-
# if address.blank?
-
1
def blank?
-
15
respond_to?(:empty?) ? empty? : !self
-
end
-
-
# An object is present if it's not <tt>blank?</tt>.
-
1
def present?
-
1335
!blank?
-
end
-
-
# Returns object if it's <tt>present?</tt> otherwise returns +nil+.
-
# <tt>object.presence</tt> is equivalent to <tt>object.present? ? object : nil</tt>.
-
#
-
# This is handy for any representation of objects where blank is the same
-
# as not present at all. For example, this simplifies a common check for
-
# HTTP POST/query parameters:
-
#
-
# state = params[:state] if params[:state].present?
-
# country = params[:country] if params[:country].present?
-
# region = state || country || 'US'
-
#
-
# ...becomes:
-
#
-
# region = params[:state].presence || params[:country].presence || 'US'
-
1
def presence
-
1223
self if present?
-
end
-
end
-
-
1
class NilClass
-
# +nil+ is blank:
-
#
-
# nil.blank? # => true
-
1
def blank?
-
298
true
-
end
-
end
-
-
1
class FalseClass
-
# +false+ is blank:
-
#
-
# false.blank? # => true
-
1
def blank?
-
5
true
-
end
-
end
-
-
1
class TrueClass
-
# +true+ is not blank:
-
#
-
# true.blank? # => false
-
1
def blank?
-
5
false
-
end
-
end
-
-
1
class Array
-
# An array is blank if it's empty:
-
#
-
# [].blank? # => true
-
# [1,2,3].blank? # => false
-
1
alias_method :blank?, :empty?
-
end
-
-
1
class Hash
-
# A hash is blank if it's empty:
-
#
-
# {}.blank? # => true
-
# { key: 'value' }.blank? # => false
-
1
alias_method :blank?, :empty?
-
end
-
-
1
class String
-
# A string is blank if it's empty or contains whitespaces only:
-
#
-
# ''.blank? # => true
-
# ' '.blank? # => true
-
# ' '.blank? # => true
-
# ' something here '.blank? # => false
-
1
def blank?
-
1537
self !~ /[^[:space:]]/
-
end
-
end
-
-
1
class Numeric #:nodoc:
-
# No number is blank:
-
#
-
# 1.blank? # => false
-
# 0.blank? # => false
-
1
def blank?
-
32
false
-
end
-
end
-
1
require 'active_support/core_ext/object/to_param'
-
1
require 'active_support/core_ext/object/to_query'
-
1
require 'active_support/core_ext/array/conversions'
-
1
require 'active_support/core_ext/hash/conversions'
-
1
require 'active_support/core_ext/object/duplicable'
-
-
1
class Object
-
# Returns a deep copy of object if it's duplicable. If it's
-
# not duplicable, returns +self+.
-
#
-
# object = Object.new
-
# dup = object.deep_dup
-
# dup.instance_variable_set(:@a, 1)
-
#
-
# object.instance_variable_defined?(:@a) #=> false
-
# dup.instance_variable_defined?(:@a) #=> true
-
1
def deep_dup
-
110
duplicable? ? dup : self
-
end
-
end
-
-
1
class Array
-
# Returns a deep copy of array.
-
#
-
# array = [1, [2, 3]]
-
# dup = array.deep_dup
-
# dup[1][2] = 4
-
#
-
# array[1][2] #=> nil
-
# dup[1][2] #=> 4
-
1
def deep_dup
-
16
map { |it| it.deep_dup }
-
end
-
end
-
-
1
class Hash
-
# Returns a deep copy of hash.
-
#
-
# hash = { a: { b: 'b' } }
-
# dup = hash.deep_dup
-
# dup[:a][:c] = 'c'
-
#
-
# hash[:a][:c] #=> nil
-
# dup[:a][:c] #=> "c"
-
1
def deep_dup
-
79
each_with_object(dup) do |(key, value), hash|
-
79
hash[key.deep_dup] = value.deep_dup
-
end
-
end
-
end
-
#--
-
# Most objects are cloneable, but not all. For example you can't dup +nil+:
-
#
-
# nil.dup # => TypeError: can't dup NilClass
-
#
-
# Classes may signal their instances are not duplicable removing +dup+/+clone+
-
# or raising exceptions from them. So, to dup an arbitrary object you normally
-
# use an optimistic approach and are ready to catch an exception, say:
-
#
-
# arbitrary_object.dup rescue object
-
#
-
# Rails dups objects in a few critical spots where they are not that arbitrary.
-
# That rescue is very expensive (like 40 times slower than a predicate), and it
-
# is often triggered.
-
#
-
# That's why we hardcode the following cases and check duplicable? instead of
-
# using that rescue idiom.
-
#++
-
1
class Object
-
# Can you safely dup this object?
-
#
-
# False for +nil+, +false+, +true+, symbol, and number objects;
-
# true otherwise.
-
1
def duplicable?
-
55
true
-
end
-
end
-
-
1
class NilClass
-
# +nil+ is not duplicable:
-
#
-
# nil.duplicable? # => false
-
# nil.dup # => TypeError: can't dup NilClass
-
1
def duplicable?
-
1
false
-
end
-
end
-
-
1
class FalseClass
-
# +false+ is not duplicable:
-
#
-
# false.duplicable? # => false
-
# false.dup # => TypeError: can't dup FalseClass
-
1
def duplicable?
-
1
false
-
end
-
end
-
-
1
class TrueClass
-
# +true+ is not duplicable:
-
#
-
# true.duplicable? # => false
-
# true.dup # => TypeError: can't dup TrueClass
-
1
def duplicable?
-
1
false
-
end
-
end
-
-
1
class Symbol
-
# Symbols are not duplicable:
-
#
-
# :my_symbol.duplicable? # => false
-
# :my_symbol.dup # => TypeError: can't dup Symbol
-
1
def duplicable?
-
25
false
-
end
-
end
-
-
1
class Numeric
-
# Numbers are not duplicable:
-
#
-
# 3.duplicable? # => false
-
# 3.dup # => TypeError: can't dup Fixnum
-
1
def duplicable?
-
43
false
-
end
-
end
-
-
1
require 'bigdecimal'
-
1
class BigDecimal
-
1
begin
-
1
BigDecimal.new('4.56').dup
-
-
def duplicable?
-
true
-
end
-
rescue TypeError
-
# can't dup, so use superclass implementation
-
end
-
end
-
1
class Object
-
# Returns true if this object is included in the argument(s). Argument must be
-
# any object which responds to +#include?+ or optionally, multiple arguments can be passed in. Usage:
-
#
-
# characters = ['Konata', 'Kagami', 'Tsukasa']
-
# 'Konata'.in?(characters) # => true
-
#
-
# character = 'Konata'
-
# character.in?('Konata', 'Kagami', 'Tsukasa') # => true
-
#
-
# This will throw an ArgumentError if a single argument is passed in and it doesn't respond
-
# to +#include?+.
-
1
def in?(*args)
-
19
if args.length > 1
-
4
args.include? self
-
else
-
15
another_object = args.first
-
15
if another_object.respond_to? :include?
-
14
another_object.include? self
-
else
-
1
raise ArgumentError.new 'The single parameter passed to #in? must respond to #include?'
-
end
-
end
-
end
-
end
-
1
class Object
-
# Returns a hash with string keys that maps instance variable names without "@" to their
-
# corresponding values.
-
#
-
# class C
-
# def initialize(x, y)
-
# @x, @y = x, y
-
# end
-
# end
-
#
-
# C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
-
1
def instance_values
-
6
Hash[instance_variables.map { |name| [name[1..-1], instance_variable_get(name)] }]
-
end
-
-
# Returns an array of instance variable names including "@".
-
#
-
# class C
-
# def initialize(x, y)
-
# @x, @y = x, y
-
# end
-
# end
-
#
-
# C.new(0, 1).instance_variable_names # => ["@y", "@x"]
-
1
def instance_variable_names
-
3
instance_variables.map { |var| var.to_s }
-
end
-
end
-
# Hack to load json gem first so we can overwrite its to_json.
-
1
begin
-
1
require 'json'
-
rescue LoadError
-
end
-
-
# The JSON gem adds a few modules to Ruby core classes containing :to_json definition, overwriting
-
# their default behavior. That said, we need to define the basic to_json method in all of them,
-
# otherwise they will always use to_json gem implementation, which is backwards incompatible in
-
# several cases (for instance, the JSON implementation for Hash does not work) with inheritance
-
# and consequently classes as ActiveSupport::OrderedHash cannot be serialized to json.
-
1
[Object, Array, FalseClass, Float, Hash, Integer, NilClass, String, TrueClass].each do |klass|
-
9
klass.class_eval do
-
# Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info.
-
9
def to_json(options = nil)
-
10
ActiveSupport::JSON.encode(self, options)
-
end
-
end
-
end
-
-
1
module Process
-
1
class Status
-
1
def as_json(options = nil)
-
{ :exitstatus => exitstatus, :pid => pid }
-
end
-
end
-
end
-
1
class Object
-
# Alias of <tt>to_s</tt>.
-
1
def to_param
-
1366
to_s
-
end
-
end
-
-
1
class NilClass
-
# Returns +self+.
-
1
def to_param
-
1
self
-
end
-
end
-
-
1
class TrueClass
-
# Returns +self+.
-
1
def to_param
-
5
self
-
end
-
end
-
-
1
class FalseClass
-
# Returns +self+.
-
1
def to_param
-
2
self
-
end
-
end
-
-
1
class Array
-
# Calls <tt>to_param</tt> on all its elements and joins the result with
-
# slashes. This is used by <tt>url_for</tt> in Action Pack.
-
1
def to_param
-
56
collect { |e| e.to_param }.join '/'
-
end
-
end
-
-
1
class Hash
-
# Returns a string representation of the receiver suitable for use as a URL
-
# query string:
-
#
-
# {name: 'David', nationality: 'Danish'}.to_param
-
# # => "name=David&nationality=Danish"
-
#
-
# An optional namespace can be passed to enclose the param names:
-
#
-
# {name: 'David', nationality: 'Danish'}.to_param('user')
-
# # => "user[name]=David&user[nationality]=Danish"
-
#
-
# The string pairs "key=value" that conform the query string
-
# are sorted lexicographically in ascending order.
-
#
-
# This method is also aliased as +to_query+.
-
1
def to_param(namespace = nil)
-
collect do |key, value|
-
30
value.to_query(namespace ? "#{namespace}[#{key}]" : key)
-
23
end.sort * '&'
-
end
-
end
-
1
require 'active_support/core_ext/object/to_param'
-
-
1
class Object
-
# Converts an object into a string suitable for use as a URL query string, using the given <tt>key</tt> as the
-
# param name.
-
#
-
# Note: This method is defined as a default implementation for all Objects for Hash#to_query to work.
-
1
def to_query(key)
-
26
require 'cgi' unless defined?(CGI) && defined?(CGI::escape)
-
26
"#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}"
-
end
-
end
-
-
1
class Array
-
# Converts an array into a string suitable for use as a URL query string,
-
# using the given +key+ as the param name.
-
#
-
# ['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding"
-
1
def to_query(key)
-
2
prefix = "#{key}[]"
-
6
collect { |value| value.to_query(prefix) }.join '&'
-
end
-
end
-
-
1
class Hash
-
1
alias_method :to_query, :to_param
-
end
-
1
class Object
-
# Invokes the public method identified by the symbol +method+, passing it any arguments
-
# and/or the block specified, just like the regular Ruby <tt>Object#public_send</tt> does.
-
#
-
# *Unlike* that method however, a +NoMethodError+ exception will *not* be raised
-
# and +nil+ will be returned instead, if the receiving object is a +nil+ object or NilClass.
-
#
-
# This is also true if the receiving object does not implemented the tried method. It will
-
# return +nil+ in that case as well.
-
#
-
# If try is called without a method to call, it will yield any given block with the object.
-
#
-
# Please also note that +try+ is defined on +Object+, therefore it won't work with
-
# subclasses of +BasicObject+. For example, using try with +SimpleDelegator+ will
-
# delegate +try+ to target instead of calling it on delegator itself.
-
#
-
# Without +try+
-
# @person && @person.name
-
# or
-
# @person ? @person.name : nil
-
#
-
# With +try+
-
# @person.try(:name)
-
#
-
# +try+ also accepts arguments and/or a block, for the method it is trying
-
# Person.try(:find, 1)
-
# @people.try(:collect) {|p| p.name}
-
#
-
# Without a method argument try will yield to the block unless the receiver is nil.
-
# @person.try { |p| "#{p.first_name} #{p.last_name}" }
-
#
-
# +try+ behaves like +Object#public_send+, unless called on +NilClass+.
-
1
def try(*a, &b)
-
4968
if a.empty? && block_given?
-
1
yield self
-
else
-
4967
public_send(*a, &b) if respond_to?(a.first)
-
end
-
end
-
-
# Same as #try, but will raise a NoMethodError exception if the receiving is not nil and
-
# does not implemented the tried method.
-
1
def try!(*a, &b)
-
3
if a.empty? && block_given?
-
yield self
-
else
-
3
public_send(*a, &b)
-
end
-
end
-
end
-
-
1
class NilClass
-
# Calling +try+ on +nil+ always returns +nil+.
-
# It becomes specially helpful when navigating through associations that may return +nil+.
-
#
-
# nil.try(:name) # => nil
-
#
-
# Without +try+
-
# @person && !@person.children.blank? && @person.children.first.name
-
#
-
# With +try+
-
# @person.try(:children).try(:first).try(:name)
-
1
def try(*args)
-
nil
-
end
-
-
1
def try!(*args)
-
nil
-
end
-
end
-
1
require 'active_support/option_merger'
-
-
1
class Object
-
# An elegant way to factor duplication out of options passed to a series of
-
# method calls. Each method called in the block, with the block variable as
-
# the receiver, will have its options merged with the default +options+ hash
-
# provided. Each method called on the block variable must take an options
-
# hash as its final argument.
-
#
-
# Without <tt>with_options></tt>, this code contains duplication:
-
#
-
# class Account < ActiveRecord::Base
-
# has_many :customers, dependent: :destroy
-
# has_many :products, dependent: :destroy
-
# has_many :invoices, dependent: :destroy
-
# has_many :expenses, dependent: :destroy
-
# end
-
#
-
# Using <tt>with_options</tt>, we can remove the duplication:
-
#
-
# class Account < ActiveRecord::Base
-
# with_options dependent: :destroy do |assoc|
-
# assoc.has_many :customers
-
# assoc.has_many :products
-
# assoc.has_many :invoices
-
# assoc.has_many :expenses
-
# end
-
# end
-
#
-
# It can also be used with an explicit receiver:
-
#
-
# I18n.with_options locale: user.locale, scope: 'newsletter' do |i18n|
-
# subject i18n.t :subject
-
# body i18n.t :body, user_name: user.name
-
# end
-
#
-
# <tt>with_options</tt> can also be nested since the call is forwarded to its receiver.
-
# Each nesting level will merge inherited defaults in addition to their own.
-
1
def with_options(options)
-
11
yield ActiveSupport::OptionMerger.new(self, options)
-
end
-
end
-
1
require "active_support/core_ext/kernel/singleton_class"
-
1
require "active_support/deprecation"
-
-
1
class Proc #:nodoc:
-
1
def bind(object)
-
1
ActiveSupport::Deprecation.warn 'Proc#bind is deprecated and will be removed in future versions'
-
-
1
block, time = self, Time.now
-
1
object.class_eval do
-
1
method_name = "__bind_#{time.to_i}_#{time.usec}"
-
1
define_method(method_name, &block)
-
1
method = instance_method(method_name)
-
1
remove_method(method_name)
-
1
method
-
end.bind(object)
-
end
-
end
-
1
require 'active_support/core_ext/range/conversions'
-
1
require 'active_support/core_ext/range/include_range'
-
1
require 'active_support/core_ext/range/overlaps'
-
1
class Range
-
1
RANGE_FORMATS = {
-
2
:db => Proc.new { |start, stop| "BETWEEN '#{start.to_s(:db)}' AND '#{stop.to_s(:db)}'" }
-
}
-
-
# Gives a human readable format of the range.
-
#
-
# (1..100).to_formatted_s # => "1..100"
-
1
def to_formatted_s(format = :default)
-
5
if formatter = RANGE_FORMATS[format]
-
2
formatter.call(first, last)
-
else
-
3
to_default_s
-
end
-
end
-
-
1
alias_method :to_default_s, :to_s
-
1
alias_method :to_s, :to_formatted_s
-
end
-
1
class Range
-
# Extends the default Range#include? to support range comparisons.
-
# (1..5).include?(1..5) # => true
-
# (1..5).include?(2..3) # => true
-
# (1..5).include?(2..6) # => false
-
#
-
# The native Range#include? behavior is untouched.
-
# ('a'..'f').include?('c') # => true
-
# (5..9).include?(11) # => false
-
1
def include_with_range?(value)
-
43206
if value.is_a?(::Range)
-
# 1...10 includes 1..9 but it does not include 1..10.
-
10
operator = exclude_end? && !value.exclude_end? ? :< : :<=
-
10
include_without_range?(value.first) && value.last.send(operator, last)
-
else
-
43196
include_without_range?(value)
-
end
-
end
-
-
1
alias_method_chain :include?, :range
-
end
-
1
class Range
-
# Compare two ranges and see if they overlap each other
-
# (1..5).overlaps?(4..6) # => true
-
# (1..5).overlaps?(7..9) # => false
-
1
def overlaps?(other)
-
6
cover?(other.first) || other.cover?(first)
-
end
-
end
-
1
class Regexp #:nodoc:
-
1
def multiline?
-
3
options & MULTILINE == MULTILINE
-
end
-
end
-
1
require 'active_support/core_ext/string/conversions'
-
1
require 'active_support/core_ext/string/filters'
-
1
require 'active_support/core_ext/string/multibyte'
-
1
require 'active_support/core_ext/string/starts_ends_with'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/core_ext/string/access'
-
1
require 'active_support/core_ext/string/xchar'
-
1
require 'active_support/core_ext/string/behavior'
-
1
require 'active_support/core_ext/string/output_safety'
-
1
require 'active_support/core_ext/string/exclude'
-
1
require 'active_support/core_ext/string/strip'
-
1
require 'active_support/core_ext/string/inquiry'
-
1
require 'active_support/core_ext/string/indent'
-
1
class String
-
# If you pass a single Fixnum, returns a substring of one character at that
-
# position. The first character of the string is at position 0, the next at
-
# position 1, and so on. If a range is supplied, a substring containing
-
# characters at offsets given by the range is returned. In both cases, if an
-
# offset is negative, it is counted from the end of the string. Returns nil
-
# if the initial offset falls outside the string. Returns an empty string if
-
# the beginning of the range is greater than the end of the string.
-
#
-
# str = "hello"
-
# str.at(0) #=> "h"
-
# str.at(1..3) #=> "ell"
-
# str.at(-2) #=> "l"
-
# str.at(-2..-1) #=> "lo"
-
# str.at(5) #=> nil
-
# str.at(5..-1) #=> ""
-
#
-
# If a Regexp is given, the matching portion of the string is returned.
-
# If a String is given, that given string is returned if it occurs in
-
# the string. In both cases, nil is returned if there is no match.
-
#
-
# str = "hello"
-
# str.at(/lo/) #=> "lo"
-
# str.at(/ol/) #=> nil
-
# str.at("lo") #=> "lo"
-
# str.at("ol") #=> nil
-
1
def at(position)
-
2
self[position]
-
end
-
-
# Returns a substring from the given position to the end of the string.
-
# If the position is negative, it is counted from the end of the string.
-
#
-
# str = "hello"
-
# str.from(0) #=> "hello"
-
# str.from(3) #=> "lo"
-
# str.from(-2) #=> "lo"
-
#
-
# You can mix it with +to+ method and do fun things like:
-
#
-
# str = "hello"
-
# str.from(0).to(-1) #=> "hello"
-
# str.from(1).to(-2) #=> "ell"
-
1
def from(position)
-
5
self[position..-1]
-
end
-
-
# Returns a substring from the beginning of the string to the given position.
-
# If the position is negative, it is counted from the end of the string.
-
#
-
# str = "hello"
-
# str.to(0) #=> "h"
-
# str.to(3) #=> "hell"
-
# str.to(-2) #=> "hell"
-
#
-
# You can mix it with +from+ method and do fun things like:
-
#
-
# str = "hello"
-
# str.from(0).to(-1) #=> "hello"
-
# str.from(1).to(-2) #=> "ell"
-
1
def to(position)
-
22
self[0..position]
-
end
-
-
# Returns the first character. If a limit is supplied, returns a substring
-
# from the beginning of the string until it reaches the limit value. If the
-
# given limit is greater than or equal to the string length, returns self.
-
#
-
# str = "hello"
-
# str.first #=> "h"
-
# str.first(1) #=> "h"
-
# str.first(2) #=> "he"
-
# str.first(0) #=> ""
-
# str.first(6) #=> "hello"
-
1
def first(limit = 1)
-
23
if limit == 0
-
1
''
-
22
elsif limit >= size
-
2
self
-
else
-
20
to(limit - 1)
-
end
-
end
-
-
# Returns the last character of the string. If a limit is supplied, returns a substring
-
# from the end of the string until it reaches the limit value (counting backwards). If
-
# the given limit is greater than or equal to the string length, returns self.
-
#
-
# str = "hello"
-
# str.last #=> "o"
-
# str.last(1) #=> "o"
-
# str.last(2) #=> "lo"
-
# str.last(0) #=> ""
-
# str.last(6) #=> "hello"
-
1
def last(limit = 1)
-
7
if limit == 0
-
1
''
-
6
elsif limit >= size
-
3
self
-
else
-
3
from(-limit)
-
end
-
end
-
end
-
1
class String
-
# Enable more predictable duck-typing on String-like classes. See <tt>Object#acts_like?</tt>.
-
1
def acts_like_string?
-
2
true
-
end
-
end
-
1
require 'date'
-
1
require 'active_support/core_ext/time/calculations'
-
-
1
class String
-
# Converts a string to a Time value.
-
# The +form+ can be either :utc or :local (default :utc).
-
#
-
# The time is parsed using Date._parse method.
-
# If +form+ is :local, then time is formatted using Time.zone
-
#
-
# "3-2-2012".to_time # => 2012-02-03 00:00:00 UTC
-
# "12:20".to_time # => ArgumentError: invalid date
-
# "2012-12-13 06:12".to_time # => 2012-12-13 06:12:00 UTC
-
# "2012-12-13T06:12".to_time # => 2012-12-13 06:12:00 UTC
-
# "2012-12-13T06:12".to_time(:local) # => 2012-12-13 06:12:00 +0100
-
1
def to_time(form = :utc)
-
8
unless blank?
-
7
date_values = ::Date._parse(self, false).
-
values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction, :offset).
-
56
map! { |arg| arg || 0 }
-
7
date_values[6] *= 1000000
-
7
offset = date_values.pop
-
-
7
::Time.send("#{form}_time", *date_values) - offset
-
end
-
end
-
-
# Converts a string to a Date value.
-
#
-
# "1-1-2012".to_date #=> Sun, 01 Jan 2012
-
# "01/01/2012".to_date #=> Sun, 01 Jan 2012
-
# "2012-12-13".to_date #=> Thu, 13 Dec 2012
-
# "12/13/2012".to_date #=> ArgumentError: invalid date
-
1
def to_date
-
2
unless blank?
-
1
date_values = ::Date._parse(self, false).values_at(:year, :mon, :mday)
-
-
1
::Date.new(*date_values)
-
end
-
end
-
-
# Converts a string to a DateTime value.
-
#
-
# "1-1-2012".to_datetime #=> Sun, 01 Jan 2012 00:00:00 +0000
-
# "01/01/2012 23:59:59".to_datetime #=> Sun, 01 Jan 2012 23:59:59 +0000
-
# "2012-12-13 12:50".to_datetime #=> Thu, 13 Dec 2012 12:50:00 +0000
-
# "12/13/2012".to_datetime #=> ArgumentError: invalid date
-
1
def to_datetime
-
5
unless blank?
-
4
date_values = ::Date._parse(self, false).
-
values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :sec_fraction).
-
32
map! { |arg| arg || 0 }
-
4
date_values[5] += date_values.pop
-
-
4
::DateTime.civil(*date_values)
-
end
-
end
-
end
-
1
require 'active_support/deprecation'
-
-
1
class String
-
1
def encoding_aware?
-
1
ActiveSupport::Deprecation.warn 'String#encoding_aware? is deprecated'
-
1
true
-
end
-
end
-
1
class String
-
# The inverse of <tt>String#include?</tt>. Returns true if the string
-
# does not include the other string.
-
#
-
# "hello".exclude? "lo" #=> false
-
# "hello".exclude? "ol" #=> true
-
# "hello".exclude? ?h #=> false
-
1
def exclude?(string)
-
2
!include?(string)
-
end
-
end
-
1
class String
-
# Returns the string, first removing all whitespace on both ends of
-
# the string, and then changing remaining consecutive whitespace
-
# groups into one space each.
-
#
-
# %{ Multi-line
-
# string }.squish # => "Multi-line string"
-
# " foo bar \n \t boo".squish # => "foo bar boo"
-
1
def squish
-
1
dup.squish!
-
end
-
-
# Performs a destructive squish. See String#squish.
-
1
def squish!
-
2
strip!
-
2
gsub!(/\s+/, ' ')
-
2
self
-
end
-
-
# Truncates a given +text+ after a given <tt>length</tt> if +text+ is longer than <tt>length</tt>:
-
#
-
# 'Once upon a time in a world far far away'.truncate(27)
-
# # => "Once upon a time in a wo..."
-
#
-
# Pass a string or regexp <tt>:separator</tt> to truncate +text+ at a natural break:
-
#
-
# 'Once upon a time in a world far far away'.truncate(27, separator: ' ')
-
# # => "Once upon a time in a..."
-
#
-
# 'Once upon a time in a world far far away'.truncate(27, separator: /\s/)
-
# # => "Once upon a time in a..."
-
#
-
# The last characters will be replaced with the <tt>:omission</tt> string (defaults to "...")
-
# for a total length not exceeding <tt>length</tt>:
-
#
-
# 'And they found that many people were sleeping better.'.truncate(25, omission: '... (continued)')
-
# # => "And they f... (continued)"
-
1
def truncate(truncate_at, options = {})
-
11
return dup unless length > truncate_at
-
-
9
options[:omission] ||= '...'
-
9
length_with_room_for_omission = truncate_at - options[:omission].length
-
9
stop = \
-
if options[:separator]
-
6
rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission
-
else
-
3
length_with_room_for_omission
-
end
-
-
9
self[0...stop] + options[:omission]
-
end
-
end
-
1
class String
-
# Same as +indent+, except it indents the receiver in-place.
-
#
-
# Returns the indented string, or +nil+ if there was nothing to indent.
-
1
def indent!(amount, indent_string=nil, indent_empty_lines=false)
-
16
indent_string = indent_string || self[/^[ \t]/] || ' '
-
16
re = indent_empty_lines ? /^/ : /^(?!$)/
-
16
gsub!(re, indent_string * amount)
-
end
-
-
# Indents the lines in the receiver:
-
#
-
# <<EOS.indent(2)
-
# def some_method
-
# some_code
-
# end
-
# EOS
-
# # =>
-
# def some_method
-
# some_code
-
# end
-
#
-
# The second argument, +indent_string+, specifies which indent string to
-
# use. The default is +nil+, which tells the method to make a guess by
-
# peeking at the first indented line, and fallback to a space if there is
-
# none.
-
#
-
# " foo".indent(2) # => " foo"
-
# "foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar"
-
# "foo".indent(2, "\t") # => "\t\tfoo"
-
#
-
# While +indent_string+ is tipically one space or tab, it may be any string.
-
#
-
# The third argument, +indent_empty_lines+, is a flag that says whether
-
# empty lines should be indented. Default is false.
-
#
-
# "foo\n\nbar".indent(2) # => " foo\n\n bar"
-
# "foo\n\nbar".indent(2, nil, true) # => " foo\n \n bar"
-
#
-
1
def indent(amount, indent_string=nil, indent_empty_lines=false)
-
26
dup.tap {|_| _.indent!(amount, indent_string, indent_empty_lines)}
-
end
-
end
-
1
require 'active_support/inflector/methods'
-
1
require 'active_support/inflector/transliterate'
-
-
# String inflections define new methods on the String class to transform names for different purposes.
-
# For instance, you can figure out the name of a table from the name of a class.
-
#
-
# 'ScaleScore'.tableize # => "scale_scores"
-
#
-
1
class String
-
# Returns the plural form of the word in the string.
-
#
-
# If the optional parameter +count+ is specified,
-
# the singular form will be returned if <tt>count == 1</tt>.
-
# For any other value of +count+ the plural will be returned.
-
#
-
# If the optional parameter +locale+ is specified,
-
# the word will be pluralized as a word of that language.
-
# By default, this parameter is set to <tt>:en</tt>.
-
# You must define your own inflection rules for languages other than English.
-
#
-
# 'post'.pluralize # => "posts"
-
# 'octopus'.pluralize # => "octopi"
-
# 'sheep'.pluralize # => "sheep"
-
# 'words'.pluralize # => "words"
-
# 'the blue mailman'.pluralize # => "the blue mailmen"
-
# 'CamelOctopus'.pluralize # => "CamelOctopi"
-
# 'apple'.pluralize(1) # => "apple"
-
# 'apple'.pluralize(2) # => "apples"
-
# 'ley'.pluralize(:es) # => "leyes"
-
# 'ley'.pluralize(1, :es) # => "ley"
-
1
def pluralize(count = nil, locale = :en)
-
95
locale = count if count.is_a?(Symbol)
-
95
if count == 1
-
1
self
-
else
-
94
ActiveSupport::Inflector.pluralize(self, locale)
-
end
-
end
-
-
# The reverse of +pluralize+, returns the singular form of a word in a string.
-
#
-
# If the optional parameter +locale+ is specified,
-
# the word will be singularized as a word of that language.
-
# By default, this paramter is set to <tt>:en</tt>.
-
# You must define your own inflection rules for languages other than English.
-
#
-
# 'posts'.singularize # => "post"
-
# 'octopi'.singularize # => "octopus"
-
# 'sheep'.singularize # => "sheep"
-
# 'word'.singularize # => "word"
-
# 'the blue mailmen'.singularize # => "the blue mailman"
-
# 'CamelOctopi'.singularize # => "CamelOctopus"
-
# 'leyes'.singularize(:es) # => "ley"
-
1
def singularize(locale = :en)
-
105
ActiveSupport::Inflector.singularize(self, locale)
-
end
-
-
# +constantize+ tries to find a declared constant with the name specified
-
# in the string. It raises a NameError when the name is not in CamelCase
-
# or is not initialized. See ActiveSupport::Inflector.constantize
-
#
-
# 'Module'.constantize # => Module
-
# 'Class'.constantize # => Class
-
# 'blargle'.constantize # => NameError: wrong constant name blargle
-
1
def constantize
-
67
ActiveSupport::Inflector.constantize(self)
-
end
-
-
# +safe_constantize+ tries to find a declared constant with the name specified
-
# in the string. It returns nil when the name is not in CamelCase
-
# or is not initialized. See ActiveSupport::Inflector.safe_constantize
-
#
-
# 'Module'.safe_constantize # => Module
-
# 'Class'.safe_constantize # => Class
-
# 'blargle'.safe_constantize # => nil
-
1
def safe_constantize
-
31
ActiveSupport::Inflector.safe_constantize(self)
-
end
-
-
# By default, +camelize+ converts strings to UpperCamelCase. If the argument to camelize
-
# is set to <tt>:lower</tt> then camelize produces lowerCamelCase.
-
#
-
# +camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces.
-
#
-
# 'active_record'.camelize # => "ActiveRecord"
-
# 'active_record'.camelize(:lower) # => "activeRecord"
-
# 'active_record/errors'.camelize # => "ActiveRecord::Errors"
-
# 'active_record/errors'.camelize(:lower) # => "activeRecord::Errors"
-
1
def camelize(first_letter = :upper)
-
605
case first_letter
-
when :upper
-
596
ActiveSupport::Inflector.camelize(self, true)
-
when :lower
-
9
ActiveSupport::Inflector.camelize(self, false)
-
end
-
end
-
1
alias_method :camelcase, :camelize
-
-
# Capitalizes all the words and replaces some characters in the string to create
-
# a nicer looking title. +titleize+ is meant for creating pretty output. It is not
-
# used in the Rails internals.
-
#
-
# +titleize+ is also aliased as +titlecase+.
-
#
-
# 'man from the boondocks'.titleize # => "Man From The Boondocks"
-
# 'x-men: the last stand'.titleize # => "X Men: The Last Stand"
-
1
def titleize
-
17
ActiveSupport::Inflector.titleize(self)
-
end
-
1
alias_method :titlecase, :titleize
-
-
# The reverse of +camelize+. Makes an underscored, lowercase form from the expression in the string.
-
#
-
# +underscore+ will also change '::' to '/' to convert namespaces to paths.
-
#
-
# 'ActiveModel'.underscore # => "active_model"
-
# 'ActiveModel::Errors'.underscore # => "active_model/errors"
-
1
def underscore
-
531
ActiveSupport::Inflector.underscore(self)
-
end
-
-
# Replaces underscores with dashes in the string.
-
#
-
# 'puni_puni'.dasherize # => "puni-puni"
-
1
def dasherize
-
ActiveSupport::Inflector.dasherize(self)
-
end
-
-
# Removes the module part from the constant expression in the string.
-
#
-
# 'ActiveRecord::CoreExtensions::String::Inflections'.demodulize # => "Inflections"
-
# 'Inflections'.demodulize # => "Inflections"
-
#
-
# See also +deconstantize+.
-
1
def demodulize
-
6
ActiveSupport::Inflector.demodulize(self)
-
end
-
-
# Removes the rightmost segment from the constant expression in the string.
-
#
-
# 'Net::HTTP'.deconstantize # => "Net"
-
# '::Net::HTTP'.deconstantize # => "::Net"
-
# 'String'.deconstantize # => ""
-
# '::String'.deconstantize # => ""
-
# ''.deconstantize # => ""
-
#
-
# See also +demodulize+.
-
1
def deconstantize
-
6
ActiveSupport::Inflector.deconstantize(self)
-
end
-
-
# Replaces special characters in a string so that it may be used as part of a 'pretty' URL.
-
#
-
# class Person
-
# def to_param
-
# "#{id}-#{name.parameterize}"
-
# end
-
# end
-
#
-
# @person = Person.find(1)
-
# # => #<Person id: 1, name: "Donald E. Knuth">
-
#
-
# <%= link_to(@person.name, person_path) %>
-
# # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>
-
1
def parameterize(sep = '-')
-
25
ActiveSupport::Inflector.parameterize(self, sep)
-
end
-
-
# Creates the name of a table like Rails does for models to table names. This method
-
# uses the +pluralize+ method on the last word in the string.
-
#
-
# 'RawScaledScorer'.tableize # => "raw_scaled_scorers"
-
# 'egg_and_ham'.tableize # => "egg_and_hams"
-
# 'fancyCategory'.tableize # => "fancy_categories"
-
1
def tableize
-
2
ActiveSupport::Inflector.tableize(self)
-
end
-
-
# Create a class name from a plural table name like Rails does for table names to models.
-
# Note that this returns a string and not a class. (To convert to an actual class
-
# follow +classify+ with +constantize+.)
-
#
-
# 'egg_and_hams'.classify # => "EggAndHam"
-
# 'posts'.classify # => "Post"
-
#
-
# Singular names are not handled correctly.
-
#
-
# 'business'.classify # => "Busines"
-
1
def classify
-
2
ActiveSupport::Inflector.classify(self)
-
end
-
-
# Capitalizes the first word, turns underscores into spaces, and strips '_id'.
-
# Like +titleize+, this is meant for creating pretty output.
-
#
-
# 'employee_salary' # => "Employee salary"
-
# 'author_id' # => "Author"
-
1
def humanize
-
3
ActiveSupport::Inflector.humanize(self)
-
end
-
-
# Creates a foreign key name from a class name.
-
# +separate_class_name_and_id_with_underscore+ sets whether
-
# the method should put '_' between the name and 'id'.
-
#
-
# 'Message'.foreign_key # => "message_id"
-
# 'Message'.foreign_key(false) # => "messageid"
-
# 'Admin::Post'.foreign_key # => "post_id"
-
1
def foreign_key(separate_class_name_and_id_with_underscore = true)
-
4
ActiveSupport::Inflector.foreign_key(self, separate_class_name_and_id_with_underscore)
-
end
-
end
-
1
require 'active_support/string_inquirer'
-
-
1
class String
-
# Wraps the current string in the <tt>ActiveSupport::StringInquirer</tt> class,
-
# which gives you a prettier way to test for equality.
-
#
-
# env = 'production'.inquiry
-
# env.production? # => true
-
# env.development? # => false
-
1
def inquiry
-
2
ActiveSupport::StringInquirer.new(self)
-
end
-
end
-
# encoding: utf-8
-
1
require 'active_support/multibyte'
-
-
1
class String
-
# == Multibyte proxy
-
#
-
# +mb_chars+ is a multibyte safe proxy for string methods.
-
#
-
# In Ruby 1.8 and older it creates and returns an instance of the ActiveSupport::Multibyte::Chars class which
-
# encapsulates the original string. A Unicode safe version of all the String methods are defined on this proxy
-
# class. If the proxy class doesn't respond to a certain method, it's forwarded to the encapsulated string.
-
#
-
# name = 'Claus Müller'
-
# name.reverse # => "rell??M sualC"
-
# name.length # => 13
-
#
-
# name.mb_chars.reverse.to_s # => "rellüM sualC"
-
# name.mb_chars.length # => 12
-
#
-
# In Ruby 1.9 and newer +mb_chars+ returns +self+ because String is (mostly) encoding aware. This means that
-
# it becomes easy to run one version of your code on multiple Ruby versions.
-
#
-
# == Method chaining
-
#
-
# All the methods on the Chars proxy which normally return a string will return a Chars object. This allows
-
# method chaining on the result of any of these methods.
-
#
-
# name.mb_chars.reverse.length # => 12
-
#
-
# == Interoperability and configuration
-
#
-
# The Chars object tries to be as interchangeable with String objects as possible: sorting and comparing between
-
# String and Char work like expected. The bang! methods change the internal string representation in the Chars
-
# object. Interoperability problems can be resolved easily with a +to_s+ call.
-
#
-
# For more information about the methods defined on the Chars proxy see ActiveSupport::Multibyte::Chars. For
-
# information about how to change the default Multibyte behavior see ActiveSupport::Multibyte.
-
1
def mb_chars
-
120
if ActiveSupport::Multibyte.proxy_class.consumes?(self)
-
119
ActiveSupport::Multibyte.proxy_class.new(self)
-
else
-
1
self
-
end
-
end
-
-
1
def is_utf8?
-
3
case encoding
-
when Encoding::UTF_8
-
3
valid_encoding?
-
when Encoding::ASCII_8BIT, Encoding::US_ASCII
-
dup.force_encoding(Encoding::UTF_8).valid_encoding?
-
else
-
false
-
end
-
end
-
end
-
1
require 'erb'
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
-
1
class ERB
-
1
module Util
-
1
HTML_ESCAPE = { '&' => '&', '>' => '>', '<' => '<', '"' => '"', "'" => ''' }
-
1
JSON_ESCAPE = { '&' => '\u0026', '>' => '\u003E', '<' => '\u003C' }
-
1
HTML_ESCAPE_ONCE_REGEXP = /["><']|&(?!([a-zA-Z]+|(#\d+));)/
-
1
JSON_ESCAPE_REGEXP = /[&"><]/
-
-
# A utility method for escaping HTML tag characters.
-
# This method is also aliased as <tt>h</tt>.
-
#
-
# In your ERB templates, use this method to escape any unsafe content. For example:
-
# <%=h @person.name %>
-
#
-
# puts html_escape('is a > 0 & a < 10?')
-
# # => is a > 0 & a < 10?
-
1
def html_escape(s)
-
15
s = s.to_s
-
15
if s.html_safe?
-
1
s
-
else
-
14
s.gsub(/[&"'><]/, HTML_ESCAPE).html_safe
-
end
-
end
-
-
# Aliasing twice issues a warning "discarding old...". Remove first to avoid it.
-
1
remove_method(:h)
-
1
alias h html_escape
-
-
1
module_function :h
-
-
1
singleton_class.send(:remove_method, :html_escape)
-
1
module_function :html_escape
-
-
# A utility method for escaping HTML without affecting existing escaped entities.
-
#
-
# html_escape_once('1 < 2 & 3')
-
# # => "1 < 2 & 3"
-
#
-
# html_escape_once('<< Accept & Checkout')
-
# # => "<< Accept & Checkout"
-
1
def html_escape_once(s)
-
result = s.to_s.gsub(HTML_ESCAPE_ONCE_REGEXP) { |special| HTML_ESCAPE[special] }
-
s.html_safe? ? result.html_safe : result
-
end
-
-
1
module_function :html_escape_once
-
-
# A utility method for escaping HTML entities in JSON strings
-
# using \uXXXX JavaScript escape sequences for string literals:
-
#
-
# json_escape('is a > 0 & a < 10?')
-
# # => is a \u003E 0 \u0026 a \u003C 10?
-
#
-
# Note that after this operation is performed the output is not
-
# valid JSON. In particular double quotes are removed:
-
#
-
# json_escape('{"name":"john","created_at":"2010-04-28T01:39:31Z","id":1}')
-
# # => {name:john,created_at:2010-04-28T01:39:31Z,id:1}
-
1
def json_escape(s)
-
result = s.to_s.gsub(JSON_ESCAPE_REGEXP) { |special| JSON_ESCAPE[special] }
-
s.html_safe? ? result.html_safe : result
-
end
-
-
1
module_function :json_escape
-
end
-
end
-
-
1
class Object
-
1
def html_safe?
-
33
false
-
end
-
end
-
-
1
class Numeric
-
1
def html_safe?
-
3
true
-
end
-
end
-
-
1
module ActiveSupport #:nodoc:
-
1
class SafeBuffer < String
-
1
UNSAFE_STRING_METHODS = %w(
-
capitalize chomp chop delete downcase gsub lstrip next reverse rstrip
-
slice squeeze strip sub succ swapcase tr tr_s upcase prepend
-
)
-
-
1
alias_method :original_concat, :concat
-
1
private :original_concat
-
-
1
class SafeConcatError < StandardError
-
1
def initialize
-
1
super 'Could not concatenate to the buffer because it is not html safe.'
-
end
-
end
-
-
1
def [](*args)
-
5
if args.size < 2
-
1
super
-
else
-
4
if html_safe?
-
3
new_safe_buffer = super
-
6
new_safe_buffer.instance_eval { @html_safe = true }
-
3
new_safe_buffer
-
else
-
1
to_str[*args]
-
end
-
end
-
end
-
-
1
def safe_concat(value)
-
1
raise SafeConcatError unless html_safe?
-
original_concat(value)
-
end
-
-
1
def initialize(*)
-
75
@html_safe = true
-
75
super
-
end
-
-
1
def initialize_copy(other)
-
9
super
-
9
@html_safe = other.html_safe?
-
end
-
-
1
def clone_empty
-
3
self[0, 0]
-
end
-
-
1
def concat(value)
-
15
if !html_safe? || value.html_safe?
-
8
super(value)
-
else
-
7
super(ERB::Util.h(value))
-
end
-
end
-
1
alias << concat
-
-
1
def +(other)
-
5
dup.concat(other)
-
end
-
-
1
def %(args)
-
3
args = Array(args).map do |arg|
-
5
if !html_safe? || arg.html_safe?
-
1
arg
-
else
-
4
ERB::Util.h(arg)
-
end
-
end
-
-
3
self.class.new(super(args))
-
end
-
-
1
def html_safe?
-
64
defined?(@html_safe) && @html_safe
-
end
-
-
1
def to_s
-
6
self
-
end
-
-
1
def to_param
-
3
to_str
-
end
-
-
1
def encode_with(coder)
-
3
coder.represent_scalar nil, to_str
-
end
-
-
1
UNSAFE_STRING_METHODS.each do |unsafe_method|
-
20
if 'String'.respond_to?(unsafe_method)
-
20
class_eval <<-EOT, __FILE__, __LINE__ + 1
-
def #{unsafe_method}(*args, &block) # def capitalize(*args, &block)
-
to_str.#{unsafe_method}(*args, &block) # to_str.capitalize(*args, &block)
-
end # end
-
-
def #{unsafe_method}!(*args) # def capitalize!(*args)
-
@html_safe = false # @html_safe = false
-
super # super
-
end # end
-
EOT
-
end
-
end
-
end
-
end
-
-
1
class String
-
1
def html_safe
-
46
ActiveSupport::SafeBuffer.new(self)
-
end
-
end
-
1
class String
-
1
alias_method :starts_with?, :start_with?
-
1
alias_method :ends_with?, :end_with?
-
end
-
1
require 'active_support/core_ext/object/try'
-
-
1
class String
-
# Strips indentation in heredocs.
-
#
-
# For example in
-
#
-
# if options[:usage]
-
# puts <<-USAGE.strip_heredoc
-
# This command does such and such.
-
#
-
# Supported options are:
-
# -h This message
-
# ...
-
# USAGE
-
# end
-
#
-
# the user would see the usage message aligned against the left margin.
-
#
-
# Technically, it looks for the least indented line in the whole string, and removes
-
# that amount of leading whitespace.
-
1
def strip_heredoc
-
7
indent = scan(/^[ \t]*(?=\S)/).min.try(:size) || 0
-
7
gsub(/^[ \t]{#{indent}}/, '')
-
end
-
end
-
1
begin
-
# See http://fast-xs.rubyforge.org/ by Eric Wong.
-
# Also included with hpricot.
-
1
require 'fast_xs'
-
rescue LoadError
-
# fast_xs extension unavailable
-
else
-
begin
-
require 'builder'
-
rescue LoadError
-
# builder demands the first shot at defining String#to_xs
-
end
-
-
class String
-
alias_method :original_xs, :to_xs if method_defined?(:to_xs)
-
alias_method :to_xs, :fast_xs
-
end
-
end
-
1
require 'active_support/core_ext/time/acts_like'
-
1
require 'active_support/core_ext/time/calculations'
-
1
require 'active_support/core_ext/time/conversions'
-
1
require 'active_support/core_ext/time/marshal'
-
1
require 'active_support/core_ext/time/zones'
-
1
require 'active_support/core_ext/object/acts_like'
-
-
1
class Time
-
# Duck-types as a Time-like class. See Object#acts_like?.
-
1
def acts_like_time?
-
1
true
-
end
-
end
-
1
require 'active_support/duration'
-
1
require 'active_support/core_ext/time/conversions'
-
1
require 'active_support/time_with_zone'
-
1
require 'active_support/core_ext/time/zones'
-
1
require 'active_support/core_ext/date_and_time/calculations'
-
-
1
class Time
-
1
include DateAndTime::Calculations
-
-
1
COMMON_YEAR_DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
-
-
1
class << self
-
# Overriding case equality method so that it returns true for ActiveSupport::TimeWithZone instances
-
1
def ===(other)
-
6
super || (self == Time && other.is_a?(ActiveSupport::TimeWithZone))
-
end
-
-
# Return the number of days in the given month.
-
# If no year is specified, it will use the current year.
-
1
def days_in_month(month, year = now.year)
-
51
if month == 2 && ::Date.gregorian_leap?(year)
-
3
29
-
else
-
48
COMMON_YEAR_DAYS_IN_MONTH[month]
-
end
-
end
-
-
# Returns a new Time if requested year can be accommodated by Ruby's Time class
-
# (i.e., if year is within either 1970..2038 or 1902..2038, depending on system architecture);
-
# otherwise returns a DateTime.
-
1
def time_with_datetime_fallback(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0, usec=0)
-
667
time = ::Time.send(utc_or_local, year, month, day, hour, min, sec, usec)
-
-
# This check is needed because Time.utc(y) returns a time object in the 2000s for 0 <= y <= 138.
-
667
if time.year == year
-
667
time
-
else
-
::DateTime.civil_from_format(utc_or_local, year, month, day, hour, min, sec)
-
end
-
rescue
-
::DateTime.civil_from_format(utc_or_local, year, month, day, hour, min, sec)
-
end
-
-
# Wraps class method +time_with_datetime_fallback+ with +utc_or_local+ set to <tt>:utc</tt>.
-
1
def utc_time(*args)
-
218
time_with_datetime_fallback(:utc, *args)
-
end
-
-
# Wraps class method +time_with_datetime_fallback+ with +utc_or_local+ set to <tt>:local</tt>.
-
1
def local_time(*args)
-
161
time_with_datetime_fallback(:local, *args)
-
end
-
-
# Returns <tt>Time.zone.now</tt> when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns <tt>Time.now</tt>.
-
1
def current
-
35
::Time.zone ? ::Time.zone.now : ::Time.now
-
end
-
end
-
-
# Seconds since midnight: Time.now.seconds_since_midnight
-
1
def seconds_since_midnight
-
18
to_i - change(:hour => 0).to_i + (usec / 1.0e+6)
-
end
-
-
# Returns a new Time where one or more of the elements have been changed according
-
# to the +options+ parameter. The time options (<tt>:hour</tt>, <tt>:min</tt>,
-
# <tt>:sec</tt>, <tt>:usec</tt>) reset cascadingly, so if only the hour is passed,
-
# then minute, sec, and usec is set to 0. If the hour and minute is passed, then
-
# sec and usec is set to 0. The +options+ parameter takes a hash with any of these
-
# keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:min</tt>,
-
# <tt>:sec</tt>, <tt>:usec</tt>.
-
#
-
# Time.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => Time.new(2012, 8, 1, 22, 35, 0)
-
# Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => Time.new(1981, 8, 1, 22, 35, 0)
-
# Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => Time.new(1981, 8, 29, 0, 0, 0)
-
1
def change(options)
-
675
new_year = options.fetch(:year, year)
-
675
new_month = options.fetch(:month, month)
-
675
new_day = options.fetch(:day, day)
-
675
new_hour = options.fetch(:hour, hour)
-
675
new_min = options.fetch(:min, options[:hour] ? 0 : min)
-
675
new_sec = options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec)
-
675
new_usec = options.fetch(:usec, (options[:hour] || options[:min] || options[:sec]) ? 0 : Rational(nsec, 1000))
-
-
675
if utc?
-
135
::Time.utc(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec)
-
540
elsif zone
-
515
::Time.local(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec)
-
else
-
25
::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec + (new_usec.to_r / 1000000), utc_offset)
-
end
-
end
-
-
# Uses Date to provide precise Time calculations for years, months, and days.
-
# The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>,
-
# <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>,
-
# <tt>:minutes</tt>, <tt>:seconds</tt>.
-
1
def advance(options)
-
428
unless options[:weeks].nil?
-
66
options[:weeks], partial_weeks = options[:weeks].divmod(1)
-
66
options[:days] = options.fetch(:days, 0) + 7 * partial_weeks
-
end
-
-
428
unless options[:days].nil?
-
286
options[:days], partial_days = options[:days].divmod(1)
-
286
options[:hours] = options.fetch(:hours, 0) + 24 * partial_days
-
end
-
-
428
d = to_date.advance(options)
-
428
time_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
-
428
seconds_to_advance = \
-
options.fetch(:seconds, 0) +
-
options.fetch(:minutes, 0) * 60 +
-
options.fetch(:hours, 0) * 3600
-
-
428
if seconds_to_advance.zero?
-
374
time_advanced_by_date
-
else
-
54
time_advanced_by_date.since(seconds_to_advance)
-
end
-
end
-
-
# Returns a new Time representing the time a number of seconds ago, this is basically a wrapper around the Numeric extension
-
1
def ago(seconds)
-
36
since(-seconds)
-
end
-
-
# Returns a new Time representing the time a number of seconds since the instance time
-
1
def since(seconds)
-
271
self + seconds
-
rescue
-
to_datetime.since(seconds)
-
end
-
1
alias :in :since
-
-
# Returns a new Time representing the start of the day (0:00)
-
1
def beginning_of_day
-
#(self - seconds_since_midnight).change(usec: 0)
-
64
change(:hour => 0)
-
end
-
1
alias :midnight :beginning_of_day
-
1
alias :at_midnight :beginning_of_day
-
1
alias :at_beginning_of_day :beginning_of_day
-
-
# Returns a new Time representing the end of the day, 23:59:59.999999 (.999999999 in ruby1.9)
-
1
def end_of_day
-
change(
-
:hour => 23,
-
:min => 59,
-
:sec => 59,
-
38
:usec => Rational(999999999, 1000)
-
)
-
end
-
-
# Returns a new Time representing the start of the hour (x:00)
-
1
def beginning_of_hour
-
2
change(:min => 0)
-
end
-
1
alias :at_beginning_of_hour :beginning_of_hour
-
-
# Returns a new Time representing the end of the hour, x:59:59.999999 (.999999999 in ruby1.9)
-
1
def end_of_hour
-
change(
-
:min => 59,
-
:sec => 59,
-
2
:usec => Rational(999999999, 1000)
-
)
-
end
-
-
# Returns a Range representing the whole day of the current time.
-
1
def all_day
-
3
beginning_of_day..end_of_day
-
end
-
-
# Returns a Range representing the whole week of the current time.
-
# Week starts on start_day, default is <tt>Date.week_start</tt> or <tt>config.week_start</tt> when set.
-
1
def all_week(start_day = Date.beginning_of_week)
-
2
beginning_of_week(start_day)..end_of_week(start_day)
-
end
-
-
# Returns a Range representing the whole month of the current time.
-
1
def all_month
-
1
beginning_of_month..end_of_month
-
end
-
-
# Returns a Range representing the whole quarter of the current time.
-
1
def all_quarter
-
1
beginning_of_quarter..end_of_quarter
-
end
-
-
# Returns a Range representing the whole year of the current time.
-
1
def all_year
-
1
beginning_of_year..end_of_year
-
end
-
-
1
def plus_with_duration(other) #:nodoc:
-
980
if ActiveSupport::Duration === other
-
118
other.since(self)
-
else
-
862
plus_without_duration(other)
-
end
-
end
-
1
alias_method :plus_without_duration, :+
-
1
alias_method :+, :plus_with_duration
-
-
1
def minus_with_duration(other) #:nodoc:
-
2939
if ActiveSupport::Duration === other
-
14
other.until(self)
-
else
-
2925
minus_without_duration(other)
-
end
-
end
-
1
alias_method :minus_without_duration, :-
-
1
alias_method :-, :minus_with_duration
-
-
# Time#- can also be used to determine the number of seconds between two Time instances.
-
# We're layering on additional behavior so that ActiveSupport::TimeWithZone instances
-
# are coerced into values that Time#- will recognize
-
1
def minus_with_coercion(other)
-
2940
other = other.comparable_time if other.respond_to?(:comparable_time)
-
2940
other.is_a?(DateTime) ? to_f - other.to_f : minus_without_coercion(other)
-
end
-
1
alias_method :minus_without_coercion, :-
-
1
alias_method :-, :minus_with_coercion
-
-
# Layers additional behavior on Time#<=> so that DateTime and ActiveSupport::TimeWithZone instances
-
# can be chronologically compared with a Time
-
1
def compare_with_coercion(other)
-
# we're avoiding Time#to_datetime cause it's expensive
-
2548
if other.is_a?(Time)
-
2515
compare_without_coercion(other.to_time)
-
else
-
33
to_datetime <=> other
-
end
-
end
-
1
alias_method :compare_without_coercion, :<=>
-
1
alias_method :<=>, :compare_with_coercion
-
-
# Layers additional behavior on Time#eql? so that ActiveSupport::TimeWithZone instances
-
# can be eql? to an equivalent Time
-
1
def eql_with_coercion(other)
-
# if other is an ActiveSupport::TimeWithZone, coerce a Time instance from it so we can do eql? comparison
-
7
other = other.comparable_time if other.respond_to?(:comparable_time)
-
7
eql_without_coercion(other)
-
end
-
1
alias_method :eql_without_coercion, :eql?
-
1
alias_method :eql?, :eql_with_coercion
-
-
end
-
1
require 'active_support/inflector/methods'
-
1
require 'active_support/values/time_zone'
-
-
1
class Time
-
1
DATE_FORMATS = {
-
:db => '%Y-%m-%d %H:%M:%S',
-
:number => '%Y%m%d%H%M%S',
-
:nsec => '%Y%m%d%H%M%S%9N',
-
:time => '%H:%M',
-
:short => '%d %b %H:%M',
-
:long => '%B %d, %Y %H:%M',
-
:long_ordinal => lambda { |time|
-
2
day_format = ActiveSupport::Inflector.ordinalize(time.day)
-
2
time.strftime("%B #{day_format}, %Y %H:%M")
-
},
-
:rfc822 => lambda { |time|
-
8
offset_format = time.formatted_offset(false)
-
8
time.strftime("%a, %d %b %Y %H:%M:%S #{offset_format}")
-
}
-
}
-
-
# Converts to a formatted string. See DATE_FORMATS for builtin formats.
-
#
-
# This method is aliased to <tt>to_s</tt>.
-
#
-
# time = Time.now # => Thu Jan 18 06:10:17 CST 2007
-
#
-
# time.to_formatted_s(:time) # => "06:10"
-
# time.to_s(:time) # => "06:10"
-
#
-
# time.to_formatted_s(:db) # => "2007-01-18 06:10:17"
-
# time.to_formatted_s(:number) # => "20070118061017"
-
# time.to_formatted_s(:short) # => "18 Jan 06:10"
-
# time.to_formatted_s(:long) # => "January 18, 2007 06:10"
-
# time.to_formatted_s(:long_ordinal) # => "January 18th, 2007 06:10"
-
# time.to_formatted_s(:rfc822) # => "Thu, 18 Jan 2007 06:10:17 -0600"
-
#
-
# == Adding your own time formats to +to_formatted_s+
-
# You can add your own formats to the Time::DATE_FORMATS hash.
-
# Use the format name as the hash key and either a strftime string
-
# or Proc instance that takes a time argument as the value.
-
#
-
# # config/initializers/time_formats.rb
-
# Time::DATE_FORMATS[:month_and_year] = '%B %Y'
-
# Time::DATE_FORMATS[:short_ordinal] = ->(time) { time.strftime("%B #{time.day.ordinalize}") }
-
1
def to_formatted_s(format = :default)
-
16
if formatter = DATE_FORMATS[format]
-
14
formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
-
else
-
2
to_default_s
-
end
-
end
-
1
alias_method :to_default_s, :to_s
-
1
alias_method :to_s, :to_formatted_s
-
-
# Returns the UTC offset as an +HH:MM formatted string.
-
#
-
# Time.local(2000).formatted_offset # => "-06:00"
-
# Time.local(2000).formatted_offset(false) # => "-0600"
-
1
def formatted_offset(colon = true, alternate_utc_string = nil)
-
12
utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon)
-
end
-
end
-
# Ruby 1.9.2 adds utc_offset and zone to Time, but marshaling only
-
# preserves utc_offset. Preserve zone also, even though it may not
-
# work in some edge cases.
-
1
if Time.local(2010).zone != Marshal.load(Marshal.dump(Time.local(2010))).zone
-
1
class Time
-
1
class << self
-
1
alias_method :_load_without_zone, :_load
-
1
def _load(marshaled_time)
-
13
time = _load_without_zone(marshaled_time)
-
13
time.instance_eval do
-
13
if zone = defined?(@_zone) && remove_instance_variable('@_zone')
-
13
ary = to_a
-
13
ary[0] += subsec if ary[0] == sec
-
13
ary[-1] = zone
-
13
utc? ? Time.utc(*ary) : Time.local(*ary)
-
else
-
self
-
end
-
end
-
end
-
end
-
-
1
alias_method :_dump_without_zone, :_dump
-
1
def _dump(*args)
-
18
obj = dup
-
18
obj.instance_variable_set('@_zone', zone)
-
18
obj._dump_without_zone(*args)
-
end
-
end
-
end
-
1
require 'active_support/time_with_zone'
-
-
1
class Time
-
1
@zone_default = nil
-
-
1
class << self
-
1
attr_accessor :zone_default
-
-
# Returns the TimeZone for the current request, if this has been set (via Time.zone=).
-
# If <tt>Time.zone</tt> has not been set for the current request, returns the TimeZone specified in <tt>config.time_zone</tt>.
-
1
def zone
-
147
Thread.current[:time_zone] || zone_default
-
end
-
-
# Sets <tt>Time.zone</tt> to a TimeZone object for the current request/thread.
-
#
-
# This method accepts any of the following:
-
#
-
# * A Rails TimeZone object.
-
# * An identifier for a Rails TimeZone object (e.g., "Eastern Time (US & Canada)", <tt>-5.hours</tt>).
-
# * A TZInfo::Timezone object.
-
# * An identifier for a TZInfo::Timezone object (e.g., "America/New_York").
-
#
-
# Here's an example of how you might set <tt>Time.zone</tt> on a per request basis and reset it when the request is done.
-
# <tt>current_user.time_zone</tt> just needs to return a string identifying the user's preferred time zone:
-
#
-
# class ApplicationController < ActionController::Base
-
# around_filter :set_time_zone
-
#
-
# def set_time_zone
-
# if logged_in?
-
# Time.use_zone(current_user.time_zone) { yield }
-
# else
-
# yield
-
# end
-
# end
-
# end
-
1
def zone=(time_zone)
-
90
Thread.current[:time_zone] = find_zone!(time_zone)
-
end
-
-
# Allows override of <tt>Time.zone</tt> locally inside supplied block; resets <tt>Time.zone</tt> to existing value when done.
-
1
def use_zone(time_zone)
-
10
new_zone = find_zone!(time_zone)
-
9
begin
-
9
old_zone, ::Time.zone = ::Time.zone, new_zone
-
9
yield
-
ensure
-
9
::Time.zone = old_zone
-
end
-
end
-
-
# Returns a TimeZone instance or nil, or raises an ArgumentError for invalid timezones.
-
1
def find_zone!(time_zone)
-
330
if !time_zone || time_zone.is_a?(ActiveSupport::TimeZone)
-
278
time_zone
-
else
-
# lookup timezone based on identifier (unless we've been passed a TZInfo::Timezone)
-
52
unless time_zone.respond_to?(:period_for_local)
-
51
time_zone = ActiveSupport::TimeZone[time_zone] || TZInfo::Timezone.get(time_zone)
-
end
-
-
# Return if a TimeZone instance, or wrap in a TimeZone instance if a TZInfo::Timezone
-
30
if time_zone.is_a?(ActiveSupport::TimeZone)
-
29
time_zone
-
else
-
1
ActiveSupport::TimeZone.create(time_zone.name, nil, time_zone)
-
end
-
end
-
rescue TZInfo::InvalidTimezoneIdentifier
-
15
raise ArgumentError, "Invalid Timezone: #{time_zone}"
-
end
-
-
1
def find_zone(time_zone)
-
14
find_zone!(time_zone) rescue nil
-
end
-
end
-
-
# Returns the simultaneous time in <tt>Time.zone</tt>.
-
#
-
# Time.zone = 'Hawaii' # => 'Hawaii'
-
# Time.utc(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
#
-
# This method is similar to Time#localtime, except that it uses <tt>Time.zone</tt> as the local zone
-
# instead of the operating system's time zone.
-
#
-
# You can also pass in a TimeZone instance or string that identifies a TimeZone as an argument,
-
# and the conversion will be based on that zone instead of <tt>Time.zone</tt>.
-
#
-
# Time.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00
-
1
def in_time_zone(zone = ::Time.zone)
-
209
if zone
-
207
ActiveSupport::TimeWithZone.new(utc? ? self : getutc, ::Time.find_zone!(zone))
-
else
-
2
self
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
require 'uri'
-
1
str = "\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E" # Ni-ho-nn-go in UTF-8, means Japanese.
-
1
parser = URI::Parser.new
-
-
1
unless str == parser.unescape(parser.escape(str))
-
1
URI::Parser.class_eval do
-
1
remove_method :unescape
-
1
def unescape(str, escaped = /%[a-fA-F\d]{2}/)
-
# TODO: Are we actually sure that ASCII == UTF-8?
-
# YK: My initial experiments say yes, but let's be sure please
-
1
enc = str.encoding
-
1
enc = Encoding::UTF_8 if enc == Encoding::US_ASCII
-
10
str.gsub(escaped) { [$&[1, 2].hex].pack('C') }.force_encoding(enc)
-
end
-
end
-
end
-
-
1
module URI
-
1
class << self
-
1
def parser
-
@parser ||= URI::Parser.new
-
end
-
end
-
end
-
1
require 'set'
-
1
require 'thread'
-
1
require 'pathname'
-
1
require 'active_support/core_ext/module/aliasing'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/module/introspection'
-
1
require 'active_support/core_ext/module/anonymous'
-
1
require 'active_support/core_ext/module/qualified_const'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/core_ext/load_error'
-
1
require 'active_support/core_ext/name_error'
-
1
require 'active_support/core_ext/string/starts_ends_with'
-
1
require 'active_support/inflector'
-
-
1
module ActiveSupport #:nodoc:
-
1
module Dependencies #:nodoc:
-
1
extend self
-
-
# Should we turn on Ruby warnings on the first load of dependent files?
-
1
mattr_accessor :warnings_on_first_load
-
1
self.warnings_on_first_load = false
-
-
# All files ever loaded.
-
1
mattr_accessor :history
-
1
self.history = Set.new
-
-
# All files currently loaded.
-
1
mattr_accessor :loaded
-
1
self.loaded = Set.new
-
-
# Should we load files or require them?
-
1
mattr_accessor :mechanism
-
1
self.mechanism = ENV['NO_RELOAD'] ? :require : :load
-
-
# The set of directories from which we may automatically load files. Files
-
# under these directories will be reloaded on each request in development mode,
-
# unless the directory also appears in autoload_once_paths.
-
1
mattr_accessor :autoload_paths
-
1
self.autoload_paths = []
-
-
# The set of directories from which automatically loaded constants are loaded
-
# only once. All directories in this set must also be present in +autoload_paths+.
-
1
mattr_accessor :autoload_once_paths
-
1
self.autoload_once_paths = []
-
-
# An array of qualified constant names that have been loaded. Adding a name
-
# to this array will cause it to be unloaded the next time Dependencies are
-
# cleared.
-
1
mattr_accessor :autoloaded_constants
-
1
self.autoloaded_constants = []
-
-
# An array of constant names that need to be unloaded on every request. Used
-
# to allow arbitrary constants to be marked for unloading.
-
1
mattr_accessor :explicitly_unloadable_constants
-
1
self.explicitly_unloadable_constants = []
-
-
# The logger is used for generating information on the action run-time
-
# (including benchmarking) if available. Can be set to nil for no logging.
-
# Compatible with both Ruby's own Logger and Log4r loggers.
-
1
mattr_accessor :logger
-
-
# Set to +true+ to enable logging of const_missing and file loads.
-
1
mattr_accessor :log_activity
-
1
self.log_activity = false
-
-
# The WatchStack keeps a stack of the modules being watched as files are
-
# loaded. If a file in the process of being loaded (parent.rb) triggers the
-
# load of another file (child.rb) the stack will ensure that child.rb
-
# handles the new constants.
-
#
-
# If child.rb is being autoloaded, its constants will be added to
-
# autoloaded_constants. If it was being `require`d, they will be discarded.
-
#
-
# This is handled by walking back up the watch stack and adding the constants
-
# found by child.rb to the list of original constants in parent.rb.
-
1
class WatchStack
-
1
include Enumerable
-
-
# @watching is a stack of lists of constants being watched. For instance,
-
# if parent.rb is autoloaded, the stack will look like [[Object]]. If
-
# parent.rb then requires namespace/child.rb, the stack will look like
-
# [[Object], [Namespace]].
-
-
1
def initialize
-
1
@watching = []
-
9
@stack = Hash.new { |h,k| h[k] = [] }
-
end
-
-
1
def each(&block)
-
5
@stack.each(&block)
-
end
-
-
1
def watching?
-
13
!@watching.empty?
-
end
-
-
# Returns a list of new constants found since the last call to
-
# <tt>watch_namespaces</tt>.
-
1
def new_constants
-
80
constants = []
-
-
# Grab the list of namespaces that we're looking for new constants under
-
80
@watching.last.each do |namespace|
-
# Retrieve the constants that were present under the namespace when watch_namespaces
-
# was originally called
-
75
original_constants = @stack[namespace].last
-
-
75
mod = Inflector.constantize(namespace) if Dependencies.qualified_const_defined?(namespace)
-
75
next unless mod.is_a?(Module)
-
-
# Get a list of the constants that were added
-
75
new_constants = mod.local_constants - original_constants
-
-
# self[namespace] returns an Array of the constants that are being evaluated
-
# for that namespace. For instance, if parent.rb requires child.rb, the first
-
# element of self[Object] will be an Array of the constants that were present
-
# before parent.rb was required. The second element will be an Array of the
-
# constants that were present before child.rb was required.
-
75
@stack[namespace].each do |namespace_constants|
-
93
namespace_constants.concat(new_constants)
-
end
-
-
# Normalize the list of new constants, and add them to the list we will return
-
75
new_constants.each do |suffix|
-
66
constants << ([namespace, suffix] - ["Object"]).join("::")
-
end
-
end
-
80
constants
-
ensure
-
# A call to new_constants is always called after a call to watch_namespaces
-
80
pop_modules(@watching.pop)
-
end
-
-
# Add a set of modules to the watch stack, remembering the initial
-
# constants.
-
1
def watch_namespaces(namespaces)
-
@watching << namespaces.map do |namespace|
-
76
module_name = Dependencies.to_constant_name(namespace)
-
76
original_constants = Dependencies.qualified_const_defined?(module_name) ?
-
Inflector.constantize(module_name).local_constants : []
-
-
75
@stack[module_name] << original_constants
-
75
module_name
-
81
end
-
end
-
-
1
private
-
1
def pop_modules(modules)
-
155
modules.each { |mod| @stack[mod].pop }
-
end
-
end
-
-
# An internal stack used to record which constants are loaded by any block.
-
1
mattr_accessor :constant_watch_stack
-
1
self.constant_watch_stack = WatchStack.new
-
-
# Module includes this module.
-
1
module ModuleConstMissing #:nodoc:
-
1
def self.append_features(base)
-
3
base.class_eval do
-
# Emulate #exclude via an ivar
-
3
return if defined?(@_const_missing) && @_const_missing
-
2
@_const_missing = instance_method(:const_missing)
-
2
remove_method(:const_missing)
-
end
-
2
super
-
end
-
-
1
def self.exclude_from(base)
-
1
base.class_eval do
-
1
define_method :const_missing, @_const_missing
-
1
@_const_missing = nil
-
end
-
end
-
-
1
def const_missing(const_name)
-
# The interpreter does not pass nesting information, and in the
-
# case of anonymous modules we cannot even make the trade-off of
-
# assuming their name reflects the nesting. Resort to Object as
-
# the only meaningful guess we can make.
-
188
from_mod = anonymous? ? ::Object : self
-
188
Dependencies.load_missing_constant(from_mod, const_name)
-
end
-
-
1
def unloadable(const_desc = self)
-
5
super(const_desc)
-
end
-
end
-
-
# Object includes this module.
-
1
module Loadable #:nodoc:
-
1
def self.exclude_from(base)
-
2
base.class_eval { define_method(:load, Kernel.instance_method(:load)) }
-
end
-
-
1
def require_or_load(file_name)
-
Dependencies.require_or_load(file_name)
-
end
-
-
1
def require_dependency(file_name, message = "No such file to load -- %s")
-
34
unless file_name.is_a?(String)
-
raise ArgumentError, "the file name must be a String -- you passed #{file_name.inspect}"
-
end
-
-
34
Dependencies.depend_on(file_name, message)
-
end
-
-
1
def load_dependency(file)
-
1849
if Dependencies.load? && ActiveSupport::Dependencies.constant_watch_stack.watching?
-
10
Dependencies.new_constants_in(Object) { yield }
-
else
-
1844
yield
-
end
-
rescue Exception => exception # errors from loading file
-
14
exception.blame_file! file
-
14
raise
-
end
-
-
1
def load(file, wrap = false)
-
3
result = false
-
6
load_dependency(file) { result = super }
-
2
result
-
end
-
-
1
def require(file)
-
1846
result = false
-
3692
load_dependency(file) { result = super }
-
1833
result
-
end
-
-
# Mark the given constant as unloadable. Unloadable constants are removed
-
# each time dependencies are cleared.
-
#
-
# Note that marking a constant for unloading need only be done once. Setup
-
# or init scripts may list each unloadable constant that may need unloading;
-
# each constant will be removed for every subsequent clear, as opposed to
-
# for the first clear.
-
#
-
# The provided constant descriptor may be a (non-anonymous) module or class,
-
# or a qualified constant name as a string or symbol.
-
#
-
# Returns +true+ if the constant was not previously marked for unloading,
-
# +false+ otherwise.
-
1
def unloadable(const_desc)
-
5
Dependencies.mark_for_unload const_desc
-
end
-
end
-
-
# Exception file-blaming.
-
1
module Blamable #:nodoc:
-
1
def blame_file!(file)
-
14
(@blamed_files ||= []).unshift file
-
end
-
-
1
def blamed_files
-
2
@blamed_files ||= []
-
end
-
-
1
def describe_blame
-
return nil if blamed_files.empty?
-
"This error occurred while loading the following files:\n #{blamed_files.join "\n "}"
-
end
-
-
1
def copy_blame!(exc)
-
2
@blamed_files = exc.blamed_files.clone
-
2
self
-
end
-
end
-
-
1
def hook!
-
6
Object.class_eval { include Loadable }
-
6
Module.class_eval { include ModuleConstMissing }
-
6
Exception.class_eval { include Blamable }
-
end
-
-
1
def unhook!
-
1
ModuleConstMissing.exclude_from(Module)
-
1
Loadable.exclude_from(Object)
-
end
-
-
1
def load?
-
1920
mechanism == :load
-
end
-
-
1
def depend_on(file_name, message = "No such file to load -- %s.rb")
-
34
path = search_for_file(file_name)
-
34
require_or_load(path || file_name)
-
rescue LoadError => load_error
-
2
if file_name = load_error.message[/ -- (.*?)(\.rb)?$/, 1]
-
2
load_error.message.replace(message % file_name)
-
2
load_error.copy_blame!(load_error)
-
end
-
2
raise
-
end
-
-
1
def clear
-
93
log_call
-
93
loaded.clear
-
93
remove_unloadable_constants!
-
end
-
-
1
def require_or_load(file_name, const_path = nil)
-
82
log_call file_name, const_path
-
82
file_name = $` if file_name =~ /\.rb\z/
-
82
expanded = File.expand_path(file_name)
-
82
return if loaded.include?(expanded)
-
-
# Record that we've seen this file *before* loading it to avoid an
-
# infinite loop with mutual dependencies.
-
71
loaded << expanded
-
-
71
begin
-
71
if load?
-
66
log "loading #{file_name}"
-
-
# Enable warnings if this file has not been loaded before and
-
# warnings_on_first_load is set.
-
66
load_args = ["#{file_name}.rb"]
-
66
load_args << const_path unless const_path.nil?
-
-
66
if !warnings_on_first_load or history.include?(expanded)
-
65
result = load_file(*load_args)
-
else
-
2
enable_warnings { result = load_file(*load_args) }
-
end
-
else
-
5
log "requiring #{file_name}"
-
5
result = require file_name
-
end
-
rescue Exception
-
19
loaded.delete expanded
-
19
raise
-
end
-
-
# Record history *after* loading so first load gets warnings.
-
52
history << expanded
-
52
result
-
end
-
-
# Is the provided constant path defined?
-
1
def qualified_const_defined?(path)
-
1416
Object.qualified_const_defined?(path.sub(/^::/, ''), false)
-
end
-
-
# Given +path+, a filesystem path to a ruby file, return an array of
-
# constant paths which would cause Dependencies to attempt to load this
-
# file.
-
1
def loadable_constants_for_path(path, bases = autoload_paths)
-
72
path = $` if path =~ /\.rb\z/
-
72
expanded_path = File.expand_path(path)
-
72
paths = []
-
-
72
bases.each do |root|
-
70
expanded_root = File.expand_path(root)
-
70
next unless %r{\A#{Regexp.escape(expanded_root)}(/|\\)} =~ expanded_path
-
-
67
nesting = expanded_path[(expanded_root.size)..-1]
-
67
nesting = nesting[1..-1] if nesting && nesting[0] == ?/
-
67
next if nesting.blank?
-
-
67
paths << nesting.camelize
-
end
-
-
72
paths.uniq!
-
72
paths
-
end
-
-
# Search for a file in autoload_paths matching the provided suffix.
-
1
def search_for_file(path_suffix)
-
228
path_suffix = path_suffix.sub(/(\.rb)?$/, ".rb")
-
-
228
autoload_paths.each do |root|
-
152
path = File.join(root, path_suffix)
-
152
return path if File.file? path
-
end
-
nil # Gee, I sure wish we had first_match ;-)
-
end
-
-
# Does the provided path_suffix correspond to an autoloadable module?
-
# Instead of returning a boolean, the autoload base for this module is
-
# returned.
-
1
def autoloadable_module?(path_suffix)
-
139
autoload_paths.each do |load_path|
-
72
return load_path if File.directory? File.join(load_path, path_suffix)
-
end
-
nil
-
end
-
-
1
def load_once_path?(path)
-
# to_s works around a ruby1.9 issue where #starts_with?(Pathname) will always return false
-
53
autoload_once_paths.any? { |base| path.starts_with? base.to_s }
-
end
-
-
# Attempt to autoload the provided module name by searching for a directory
-
# matching the expected path suffix. If found, the module is created and
-
# assigned to +into+'s constants with the name +const_name+. Provided that
-
# the directory was loaded from a reloadable base path, it is added to the
-
# set of constants that are to be unloaded.
-
1
def autoload_module!(into, const_name, qualified_name, path_suffix)
-
139
return nil unless base_path = autoloadable_module?(path_suffix)
-
13
mod = Module.new
-
13
into.const_set const_name, mod
-
13
autoloaded_constants << qualified_name unless autoload_once_paths.include?(base_path)
-
13
mod
-
end
-
-
# Load the file at the provided path. +const_paths+ is a set of qualified
-
# constant names. When loading the file, Dependencies will watch for the
-
# addition of these constants. Each that is defined will be marked as
-
# autoloaded, and will be removed when Dependencies.clear is next called.
-
#
-
# If the second parameter is left off, then Dependencies will construct a
-
# set of names that the file at +path+ may define. See
-
# +loadable_constants_for_path+ for more details.
-
1
def load_file(path, const_paths = loadable_constants_for_path(path))
-
66
log_call path, const_paths
-
66
const_paths = [const_paths].compact unless const_paths.is_a? Array
-
127
parent_paths = const_paths.collect { |const_path| const_path[/.*(?=::)/] || :Object }
-
-
66
result = nil
-
66
newly_defined_paths = new_constants_in(*parent_paths) do
-
66
result = Kernel.load path
-
end
-
-
49
autoloaded_constants.concat newly_defined_paths unless load_once_path?(path)
-
49
autoloaded_constants.uniq!
-
49
log "loading #{path} defined #{newly_defined_paths * ', '}" unless newly_defined_paths.empty?
-
49
result
-
end
-
-
# Returns the constant path for the provided parent and constant name.
-
1
def qualified_name_for(mod, name)
-
216
mod_name = to_constant_name mod
-
216
mod_name == "Object" ? name.to_s : "#{mod_name}::#{name}"
-
end
-
-
# Load the constant named +const_name+ which is missing from +from_mod+. If
-
# it is not possible to load the constant into from_mod, try its parent
-
# module using +const_missing+.
-
1
def load_missing_constant(from_mod, const_name)
-
190
log_call from_mod, const_name
-
-
190
unless qualified_const_defined?(from_mod.name) && Inflector.constantize(from_mod.name).equal?(from_mod)
-
1
raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!"
-
end
-
-
189
raise NameError, "#{from_mod} is not missing constant #{const_name}!" if from_mod.const_defined?(const_name, false)
-
-
188
qualified_name = qualified_name_for from_mod, const_name
-
188
path_suffix = qualified_name.underscore
-
-
188
file_path = search_for_file(path_suffix)
-
-
188
if file_path
-
49
expanded = File.expand_path(file_path)
-
49
expanded.sub!(/\.rb\z/, '')
-
-
49
if loaded.include?(expanded)
-
1
raise "Circular dependency detected while autoloading constant #{qualified_name}"
-
else
-
48
require_or_load(expanded)
-
36
raise LoadError, "Unable to autoload constant #{qualified_name}, expected #{file_path} to define it" unless from_mod.const_defined?(const_name, false)
-
36
return from_mod.const_get(const_name)
-
end
-
elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
-
13
return mod
-
126
elsif (parent = from_mod.parent) && parent != from_mod &&
-
81
! from_mod.parents.any? { |p| p.const_defined?(const_name, false) }
-
# If our parents do not have a constant named +const_name+ then we are free
-
# to attempt to load upwards. If they do have such a constant, then this
-
# const_missing must be due to from_mod::const_name, which should not
-
# return constants from from_mod's parents.
-
51
begin
-
# Since Ruby does not pass the nesting at the point the unknown
-
# constant triggered the callback we cannot fully emulate constant
-
# name lookup and need to make a trade-off: we are going to assume
-
# that the nesting in the body of Foo::Bar is [Foo::Bar, Foo] even
-
# though it might not be. Counterexamples are
-
#
-
# class Foo::Bar
-
# Module.nesting # => [Foo::Bar]
-
# end
-
#
-
# or
-
#
-
# module M::N
-
# module S::T
-
# Module.nesting # => [S::T, M::N]
-
# end
-
# end
-
#
-
# for example.
-
51
return parent.const_missing(const_name)
-
rescue NameError => e
-
22
raise unless e.missing_name? qualified_name_for(parent, const_name)
-
end
-
end
-
-
95
raise NameError,
-
"uninitialized constant #{qualified_name}",
-
2349
caller.reject { |l| l.starts_with? __FILE__ }
-
end
-
-
# Remove the constants that have been autoloaded, and those that have been
-
# marked for unloading. Before each constant is removed a callback is sent
-
# to its class/module if it implements +before_remove_const+.
-
#
-
# The callback implementation should be restricted to cleaning up caches, etc.
-
# as the environment will be in an inconsistent state, e.g. other constants
-
# may have already been unloaded and not accessible.
-
1
def remove_unloadable_constants!
-
146
autoloaded_constants.each { |const| remove_constant const }
-
93
autoloaded_constants.clear
-
93
Reference.clear!
-
97
explicitly_unloadable_constants.each { |const| remove_constant const }
-
end
-
-
1
class ClassCache
-
1
def initialize
-
13
@store = Hash.new
-
end
-
-
1
def empty?
-
10
@store.empty?
-
end
-
-
1
def key?(key)
-
2
@store.key?(key)
-
end
-
-
1
def get(key)
-
46
key = key.name if key.respond_to?(:name)
-
46
@store[key] ||= Inflector.constantize(key)
-
end
-
1
alias :[] :get
-
-
1
def safe_get(key)
-
2
key = key.name if key.respond_to?(:name)
-
2
@store[key] ||= Inflector.safe_constantize(key)
-
end
-
-
1
def store(klass)
-
8
return self unless klass.respond_to?(:name)
-
6
raise(ArgumentError, 'anonymous classes cannot be cached') if klass.name.empty?
-
6
@store[klass.name] = klass
-
6
self
-
end
-
-
1
def clear!
-
94
@store.clear
-
end
-
end
-
-
1
Reference = ClassCache.new
-
-
# Store a reference to a class +klass+.
-
1
def reference(klass)
-
1
Reference.store klass
-
end
-
-
# Get the reference for class named +name+.
-
# Raises an exception if referenced class does not exist.
-
1
def constantize(name)
-
37
Reference.get(name)
-
end
-
-
# Get the reference for class named +name+ if one exists.
-
# Otherwise returns +nil+.
-
1
def safe_constantize(name)
-
Reference.safe_get(name)
-
end
-
-
# Determine if the given constant has been automatically loaded.
-
1
def autoloaded?(desc)
-
# No name => anonymous module.
-
1028
return false if desc.is_a?(Module) && desc.anonymous?
-
1001
name = to_constant_name desc
-
1001
return false unless qualified_const_defined? name
-
994
return autoloaded_constants.include?(name)
-
end
-
-
# Will the provided constant descriptor be unloaded?
-
1
def will_unload?(const_desc)
-
autoloaded?(const_desc) ||
-
explicitly_unloadable_constants.include?(to_constant_name(const_desc))
-
end
-
-
# Mark the provided constant name for unloading. This constant will be
-
# unloaded on each request, not just the next one.
-
1
def mark_for_unload(const_desc)
-
5
name = to_constant_name const_desc
-
4
if explicitly_unloadable_constants.include? name
-
1
false
-
else
-
3
explicitly_unloadable_constants << name
-
3
true
-
end
-
end
-
-
# Run the provided block and detect the new constants that were loaded during
-
# its execution. Constants may only be regarded as 'new' once -- so if the
-
# block calls +new_constants_in+ again, then the constants defined within the
-
# inner call will not be reported in this one.
-
#
-
# If the provided block does not run to completion, and instead raises an
-
# exception, any new constants are regarded as being only partially defined
-
# and will be removed immediately.
-
1
def new_constants_in(*descs)
-
81
log_call(*descs)
-
-
81
constant_watch_stack.watch_namespaces(descs)
-
80
aborting = true
-
-
80
begin
-
80
yield # Now yield to the code that is to define new constants.
-
62
aborting = false
-
ensure
-
80
new_constants = constant_watch_stack.new_constants
-
-
80
log "New constants: #{new_constants * ', '}"
-
80
return new_constants unless aborting
-
-
18
log "Error during loading, removing partially loaded constants "
-
26
new_constants.each { |c| remove_constant(c) }.clear
-
end
-
-
[]
-
end
-
-
# Convert the provided const desc to a qualified constant name (as a string).
-
# A module, class, symbol, or string may be provided.
-
1
def to_constant_name(desc) #:nodoc:
-
1298
case desc
-
36
when String then desc.sub(/^::/, '')
-
56
when Symbol then desc.to_s
-
when Module
-
desc.name.presence ||
-
1206
raise(ArgumentError, "Anonymous modules have no name to be referenced by")
-
else raise TypeError, "Not a valid constant descriptor: #{desc.inspect}"
-
end
-
end
-
-
1
def remove_constant(const) #:nodoc:
-
67
return false unless qualified_const_defined? const
-
-
# Normalize ::Foo, Foo, Object::Foo, and ::Object::Foo to Object::Foo
-
36
names = const.to_s.sub(/^::(Object)?/, 'Object::').split("::")
-
36
to_remove = names.pop
-
36
parent = Inflector.constantize(names * '::')
-
-
36
log "removing constant #{const}"
-
36
constantized = constantize(const)
-
36
constantized.before_remove_const if constantized.respond_to?(:before_remove_const)
-
72
parent.instance_eval { remove_const to_remove }
-
-
36
true
-
end
-
-
1
protected
-
1
def log_call(*args)
-
512
if log_activity?
-
arg_str = args.collect { |arg| arg.inspect } * ', '
-
/in `([a-z_\?\!]+)'/ =~ caller(1).first
-
selector = $1 || '<unknown>'
-
log "called #{selector}(#{arg_str})"
-
end
-
end
-
-
1
def log(msg)
-
246
logger.debug "Dependencies: #{msg}" if log_activity?
-
end
-
-
1
def log_activity?
-
758
logger && log_activity
-
end
-
end
-
end
-
-
1
ActiveSupport::Dependencies.hook!
-
1
require "active_support/inflector/methods"
-
-
1
module ActiveSupport
-
# Autoload and eager load conveniences for your library.
-
#
-
# This module allows you to define autoloads based on
-
# Rails conventions (i.e. no need to define the path
-
# it is automatically guessed based on the filename)
-
# and also define a set of constants that needs to be
-
# eager loaded:
-
#
-
# module MyLib
-
# extend ActiveSupport::Autoload
-
#
-
# autoload :Model
-
#
-
# eager_autoload do
-
# autoload :Cache
-
# end
-
# end
-
#
-
# Then your library can be eager loaded by simply calling:
-
#
-
# MyLib.eager_load!
-
1
module Autoload
-
1
def self.extended(base) # :nodoc:
-
13
base.class_eval do
-
13
@_autoloads = {}
-
13
@_under_path = nil
-
13
@_at_path = nil
-
13
@_eager_autoload = false
-
end
-
end
-
-
1
def autoload(const_name, path = @_at_path)
-
157
unless path
-
114
full = [name, @_under_path, const_name.to_s, path].compact.join("::")
-
114
path = Inflector.underscore(full)
-
end
-
-
157
if @_eager_autoload
-
60
@_autoloads[const_name] = path
-
end
-
-
157
super const_name, path
-
end
-
-
1
def autoload_under(path)
-
2
@_under_path, old_path = path, @_under_path
-
2
yield
-
ensure
-
2
@_under_path = old_path
-
end
-
-
1
def autoload_at(path)
-
3
@_at_path, old_path = path, @_at_path
-
3
yield
-
ensure
-
3
@_at_path = old_path
-
end
-
-
1
def eager_autoload
-
9
old_eager, @_eager_autoload = @_eager_autoload, true
-
9
yield
-
ensure
-
9
@_eager_autoload = old_eager
-
end
-
-
1
def eager_load!
-
@_autoloads.values.each { |file| require file }
-
end
-
-
1
def autoloads
-
@_autoloads
-
end
-
end
-
end
-
1
require 'singleton'
-
-
1
module ActiveSupport
-
# \Deprecation specifies the API used by Rails to deprecate methods, instance
-
# variables, objects and constants.
-
1
class Deprecation
-
# active_support.rb sets an autoload for ActiveSupport::Deprecation.
-
#
-
# If these requires were at the top of the file the constant would not be
-
# defined by the time their files were loaded. Since some of them reopen
-
# ActiveSupport::Deprecation its autoload would be triggered, resulting in
-
# a circular require warning for active_support/deprecation.rb.
-
#
-
# So, we define the constant first, and load dependencies later.
-
1
require 'active_support/deprecation/instance_delegator'
-
1
require 'active_support/deprecation/behaviors'
-
1
require 'active_support/deprecation/reporting'
-
1
require 'active_support/deprecation/method_wrappers'
-
1
require 'active_support/deprecation/proxy_wrappers'
-
1
require 'active_support/core_ext/module/deprecation'
-
-
1
include Singleton
-
1
include InstanceDelegator
-
1
include Behavior
-
1
include Reporting
-
1
include MethodWrapper
-
-
# The version the deprecated behavior will be removed, by default.
-
1
attr_accessor :deprecation_horizon
-
-
# It accepts two parameters on initialization. The first is an version of library
-
# and the second is an library name
-
#
-
# ActiveSupport::Deprecation.new('2.0', 'MyLibrary')
-
1
def initialize(deprecation_horizon = '4.1', gem_name = 'Rails')
-
7
self.gem_name = gem_name
-
7
self.deprecation_horizon = deprecation_horizon
-
# By default, warnings are not silenced and debugging is off.
-
7
self.silenced = false
-
7
self.debug = false
-
end
-
end
-
end
-
1
require "active_support/notifications"
-
-
1
module ActiveSupport
-
1
class Deprecation
-
# Default warning behaviors per Rails.env.
-
1
DEFAULT_BEHAVIORS = {
-
:stderr => Proc.new { |message, callstack|
-
2
$stderr.puts(message)
-
2
$stderr.puts callstack.join("\n ") if debug
-
},
-
:log => Proc.new { |message, callstack|
-
logger =
-
if defined?(Rails) && Rails.logger
-
Rails.logger
-
else
-
require 'active_support/logger'
-
ActiveSupport::Logger.new($stderr)
-
end
-
logger.warn message
-
logger.debug callstack.join("\n ") if debug
-
},
-
:notify => Proc.new { |message, callstack|
-
ActiveSupport::Notifications.instrument("deprecation.rails",
-
:message => message, :callstack => callstack)
-
},
-
:silence => Proc.new { |message, callstack| }
-
}
-
-
1
module Behavior
-
# Whether to print a backtrace along with the warning.
-
1
attr_accessor :debug
-
-
# Returns the current behavior or if one isn't set, defaults to +:stderr+.
-
1
def behavior
-
90
@behavior ||= [DEFAULT_BEHAVIORS[:stderr]]
-
end
-
-
# Sets the behavior to the specified value. Can be a single value, array,
-
# or an object that responds to +call+.
-
#
-
# Available behaviors:
-
#
-
# [+stderr+] Log all deprecation warnings to +$stderr+.
-
# [+log+] Log all deprecation warnings to +Rails.logger+.
-
# [+notify+] Use +ActiveSupport::Notifications+ to notify +deprecation.rails+.
-
# [+silence+] Do nothing.
-
#
-
# Setting behaviors only affects deprecations that happen after boot time.
-
# Deprecation warnings raised by gems are not affected by this setting
-
# because they happen before Rails boots up.
-
#
-
# ActiveSupport::Deprecation.behavior = :stderr
-
# ActiveSupport::Deprecation.behavior = [:stderr, :log]
-
# ActiveSupport::Deprecation.behavior = MyCustomHandler
-
# ActiveSupport::Deprecation.behavior = proc { |message, callstack|
-
# # custom stuff
-
# }
-
1
def behavior=(behavior)
-
249
@behavior = Array(behavior).map { |b| DEFAULT_BEHAVIORS[b] || b }
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/kernel/singleton_class'
-
1
require 'active_support/core_ext/module/delegation'
-
-
1
module ActiveSupport
-
1
class Deprecation
-
1
module InstanceDelegator
-
1
def self.included(base)
-
1
base.extend(ClassMethods)
-
1
base.public_class_method :new
-
end
-
-
1
module ClassMethods
-
1
def include(included_module)
-
15
included_module.instance_methods.each { |m| method_added(m) }
-
3
super
-
end
-
-
1
def method_added(method_name)
-
15
singleton_class.delegate(method_name, to: :instance)
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/aliasing'
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
module ActiveSupport
-
1
class Deprecation
-
1
module MethodWrapper
-
# Declare that a method has been deprecated.
-
#
-
# module Fred
-
# extend self
-
#
-
# def foo; end
-
# def bar; end
-
# def baz; end
-
# end
-
#
-
# ActiveSupport::Deprecation.deprecate_methods(Fred, :foo, bar: :qux, baz: 'use Bar#baz instead')
-
# # => [:foo, :bar, :baz]
-
#
-
# Fred.foo
-
# # => "DEPRECATION WARNING: foo is deprecated and will be removed from Rails 4.1."
-
#
-
# Fred.bar
-
# # => "DEPRECATION WARNING: bar is deprecated and will be removed from Rails 4.1 (use qux instead)."
-
#
-
# Fred.baz
-
# # => "DEPRECATION WARNING: baz is deprecated and will be removed from Rails 4.1 (use Bar#baz instead)."
-
1
def deprecate_methods(target_module, *method_names)
-
7
options = method_names.extract_options!
-
7
deprecator = options.delete(:deprecator) || ActiveSupport::Deprecation.instance
-
7
method_names += options.keys
-
-
7
method_names.each do |method_name|
-
14
target_module.alias_method_chain(method_name, :deprecation) do |target, punctuation|
-
14
target_module.send(:define_method, "#{target}_with_deprecation#{punctuation}") do |*args, &block|
-
10
deprecator.deprecation_warning(method_name, options[method_name])
-
10
send(:"#{target}_without_deprecation#{punctuation}", *args, &block)
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/inflector/methods'
-
-
1
module ActiveSupport
-
1
class Deprecation
-
1
class DeprecationProxy #:nodoc:
-
1
def self.new(*args, &block)
-
37
object = args.first
-
-
37
return object unless object
-
34
super
-
end
-
-
72
instance_methods.each { |m| undef_method m unless m =~ /^__|^object_id$/ }
-
-
# Don't give a deprecation warning on inspect since test/unit and error
-
# logs rely on it for diagnostics.
-
1
def inspect
-
1
target.inspect
-
end
-
-
1
private
-
1
def method_missing(called, *args, &block)
-
6
warn caller, called, args
-
6
target.__send__(called, *args, &block)
-
end
-
end
-
-
# This DeprecatedObjectProxy transforms object to depracated object.
-
#
-
# @old_object = DeprecatedObjectProxy.new(Object.new, "Don't use this object anymore!")
-
# @old_object = DeprecatedObjectProxy.new(Object.new, "Don't use this object anymore!", deprecator_instance)
-
#
-
# When someone execute any method expect +inspect+ on proxy object this will
-
# trigger +warn+ method on +deprecator_instance+.
-
#
-
# Default deprecator is <tt>ActiveSupport::Deprecation</tt>
-
1
class DeprecatedObjectProxy < DeprecationProxy
-
1
def initialize(object, message, deprecator = ActiveSupport::Deprecation.instance)
-
@object = object
-
@message = message
-
@deprecator = deprecator
-
end
-
-
1
private
-
1
def target
-
@object
-
end
-
-
1
def warn(callstack, called, args)
-
@deprecator.warn(@message, callstack)
-
end
-
end
-
-
# This DeprecatedInstanceVariableProxy transforms instance variable to
-
# depracated instance variable.
-
#
-
# class Example
-
# def initialize(deprecator)
-
# @request = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new(self, :request, :@request, deprecator)
-
# @_request = :a_request
-
# end
-
#
-
# def request
-
# @_request
-
# end
-
#
-
# def old_request
-
# @request
-
# end
-
# end
-
#
-
# When someone execute any method on @request variable this will trigger
-
# +warn+ method on +deprecator_instance+ and will fetch <tt>@_request</tt>
-
# variable via +request+ method and execute the same method on non-proxy
-
# instance variable.
-
#
-
# Default deprecator is <tt>ActiveSupport::Deprecation</tt>.
-
1
class DeprecatedInstanceVariableProxy < DeprecationProxy
-
1
def initialize(instance, method, var = "@#{method}", deprecator = ActiveSupport::Deprecation.instance)
-
31
@instance = instance
-
31
@method = method
-
31
@var = var
-
31
@deprecator = deprecator
-
end
-
-
1
private
-
1
def target
-
5
@instance.__send__(@method)
-
end
-
-
1
def warn(callstack, called, args)
-
4
@deprecator.warn("#{@var} is deprecated! Call #{@method}.#{called} instead of #{@var}.#{called}. Args: #{args.inspect}", callstack)
-
end
-
end
-
-
# This DeprecatedConstantProxy transforms constant to depracated constant.
-
#
-
# OLD_CONST = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('OLD_CONST', 'NEW_CONST')
-
# OLD_CONST = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('OLD_CONST', 'NEW_CONST', deprecator_instance)
-
#
-
# When someone use old constant this will trigger +warn+ method on
-
# +deprecator_instance+.
-
#
-
# Default deprecator is <tt>ActiveSupport::Deprecation</tt>.
-
1
class DeprecatedConstantProxy < DeprecationProxy
-
1
def initialize(old_const, new_const, deprecator = ActiveSupport::Deprecation.instance)
-
3
@old_const = old_const
-
3
@new_const = new_const
-
3
@deprecator = deprecator
-
end
-
-
1
def class
-
target.class
-
end
-
-
1
private
-
1
def target
-
2
ActiveSupport::Inflector.constantize(@new_const.to_s)
-
end
-
-
1
def warn(callstack, called, args)
-
2
@deprecator.warn("#{@old_const} is deprecated! Use #{@new_const} instead.", callstack)
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
1
class Deprecation
-
1
module Reporting
-
# Whether to print a message (silent mode)
-
1
attr_accessor :silenced
-
# Name of gem where method is deprecated
-
1
attr_accessor :gem_name
-
-
# Outputs a deprecation warning to the output configured by
-
# <tt>ActiveSupport::Deprecation.behavior</tt>.
-
#
-
# ActiveSupport::Deprecation.warn('something broke!')
-
# # => "DEPRECATION WARNING: something broke! (called from your_code.rb:1)"
-
1
def warn(message = nil, callstack = nil)
-
40
return if silenced
-
-
31
callstack ||= caller(2)
-
31
deprecation_message(callstack, message).tap do |m|
-
63
behavior.each { |b| b.call(m, callstack) }
-
end
-
end
-
-
# Silence deprecation warnings within the block.
-
#
-
# ActiveSupport::Deprecation.warn('something broke!')
-
# # => "DEPRECATION WARNING: something broke! (called from your_code.rb:1)"
-
#
-
# ActiveSupport::Deprecation.silence do
-
# ActiveSupport::Deprecation.warn('something broke!')
-
# end
-
# # => nil
-
1
def silence
-
6
old_silenced, @silenced = @silenced, true
-
6
yield
-
ensure
-
6
@silenced = old_silenced
-
end
-
-
1
def deprecation_warning(deprecated_method_name, message = nil, caller_backtrace = nil)
-
9
caller_backtrace ||= caller(2)
-
9
deprecated_method_warning(deprecated_method_name, message).tap do |msg|
-
9
warn(msg, caller_backtrace)
-
end
-
end
-
-
1
private
-
# Outputs a deprecation warning message
-
#
-
# ActiveSupport::Deprecation.deprecated_method_warning(:method_name)
-
# # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon}"
-
# ActiveSupport::Deprecation.deprecated_method_warning(:method_name, :another_method)
-
# # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon} (use another_method instead)"
-
# ActiveSupport::Deprecation.deprecated_method_warning(:method_name, "Optional message")
-
# # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon} (Optional message)"
-
1
def deprecated_method_warning(method_name, message = nil)
-
10
warning = "#{method_name} is deprecated and will be removed from #{gem_name} #{deprecation_horizon}"
-
10
case message
-
1
when Symbol then "#{warning} (use #{message} instead)"
-
3
when String then "#{warning} (#{message})"
-
6
else warning
-
end
-
end
-
-
1
def deprecation_message(callstack, message = nil)
-
31
message ||= "You are using deprecated behavior which will be removed from the next major or minor release."
-
31
message += '.' unless message =~ /\.$/
-
31
"DEPRECATION WARNING: #{message} #{deprecation_caller_message(callstack)}"
-
end
-
-
1
def deprecation_caller_message(callstack)
-
31
file, line, method = extract_callstack(callstack)
-
31
if file
-
31
if line && method
-
30
"(called from #{method} at #{file}:#{line})"
-
else
-
1
"(called from #{file}:#{line})"
-
end
-
end
-
end
-
-
1
def extract_callstack(callstack)
-
31
rails_gem_root = File.expand_path("../../../../..", __FILE__) + "/"
-
179
offending_line = callstack.find { |line| !line.start_with?(rails_gem_root) } || callstack.first
-
31
if offending_line
-
31
if md = offending_line.match(/^(.+?):(\d+)(?::in `(.*?)')?/)
-
30
md.captures
-
else
-
1
offending_line
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
# This module provides an internal implementation to track descendants
-
# which is faster than iterating through ObjectSpace.
-
1
module DescendantsTracker
-
1
@@direct_descendants = {}
-
-
1
class << self
-
1
def direct_descendants(klass)
-
6
@@direct_descendants[klass] || []
-
end
-
-
1
def descendants(klass)
-
121
arr = []
-
121
accumulate_descendants(klass, arr)
-
121
arr
-
end
-
-
1
def clear
-
5
if defined? ActiveSupport::Dependencies
-
5
@@direct_descendants.each do |klass, descendants|
-
70
if ActiveSupport::Dependencies.autoloaded?(klass)
-
7
@@direct_descendants.delete(klass)
-
else
-
989
descendants.reject! { |v| ActiveSupport::Dependencies.autoloaded?(v) }
-
end
-
end
-
else
-
@@direct_descendants.clear
-
end
-
end
-
-
# This is the only method that is not thread safe, but is only ever called
-
# during the eager loading phase.
-
1
def store_inherited(klass, descendant)
-
188
(@@direct_descendants[klass] ||= []) << descendant
-
end
-
-
1
private
-
1
def accumulate_descendants(klass, acc)
-
138
if direct_descendants = @@direct_descendants[klass]
-
12
acc.concat(direct_descendants)
-
29
direct_descendants.each { |direct_descendant| accumulate_descendants(direct_descendant, acc) }
-
end
-
end
-
end
-
-
1
def inherited(base)
-
188
DescendantsTracker.store_inherited(self, base)
-
188
super
-
end
-
-
1
def direct_descendants
-
6
DescendantsTracker.direct_descendants(self)
-
end
-
-
1
def descendants
-
11
DescendantsTracker.descendants(self)
-
end
-
end
-
end
-
1
require 'active_support/basic_object'
-
1
require 'active_support/core_ext/array/conversions'
-
1
require 'active_support/core_ext/object/acts_like'
-
-
1
module ActiveSupport
-
# Provides accurate date and time measurements using Date#advance and
-
# Time#advance, respectively. It mainly supports the methods on Numeric.
-
#
-
# 1.month.ago # equivalent to Time.now.advance(months: -1)
-
1
class Duration < BasicObject
-
1
attr_accessor :value, :parts
-
-
1
def initialize(value, parts) #:nodoc:
-
808
@value, @parts = value, parts
-
end
-
-
# Adds another Duration or a Numeric to this Duration. Numeric values
-
# are treated as seconds.
-
1
def +(other)
-
72
if Duration === other
-
71
Duration.new(value + other.value, @parts + other.parts)
-
else
-
1
Duration.new(value + other, @parts + [[:seconds, other]])
-
end
-
end
-
-
# Subtracts another Duration or a Numeric from this Duration. Numeric
-
# values are treated as seconds.
-
1
def -(other)
-
7
self + (-other)
-
end
-
-
1
def -@ #:nodoc:
-
92
Duration.new(-value, parts.map { |type,number| [type, -number] })
-
end
-
-
1
def is_a?(klass) #:nodoc:
-
329
Duration == klass || value.is_a?(klass)
-
end
-
1
alias :kind_of? :is_a?
-
-
# Returns +true+ if +other+ is also a Duration instance with the
-
# same +value+, or if <tt>other == value</tt>.
-
1
def ==(other)
-
13
if Duration === other
-
1
other.value == value
-
else
-
12
other == value
-
end
-
end
-
-
1
def self.===(other) #:nodoc:
-
4792
other.is_a?(Duration)
-
rescue ::NoMethodError
-
1
false
-
end
-
-
# Calculates a new Time or Date that is as far in the future
-
# as this Duration represents.
-
1
def since(time = ::Time.current)
-
162
sum(1, time)
-
end
-
1
alias :from_now :since
-
-
# Calculates a new Time or Date that is as far in the past
-
# as this Duration represents.
-
1
def ago(time = ::Time.current)
-
30
sum(-1, time)
-
end
-
1
alias :until :ago
-
-
1
def inspect #:nodoc:
-
20
consolidated = parts.inject(::Hash.new(0)) { |h,(l,r)| h[l] += r; h }
-
8
parts = [:years, :months, :days, :minutes, :seconds].map do |length|
-
40
n = consolidated[length]
-
40
"#{n} #{n == 1 ? length.to_s.singularize : length.to_s}" if n.nonzero?
-
end.compact
-
8
parts = ["0 seconds"] if parts.empty?
-
8
parts.to_sentence(:locale => :en)
-
end
-
-
1
def as_json(options = nil) #:nodoc:
-
to_i
-
end
-
-
1
protected
-
-
1
def sum(sign, time = ::Time.current) #:nodoc:
-
192
parts.inject(time) do |t,(type,number)|
-
204
if t.acts_like?(:time) || t.acts_like?(:date)
-
203
if type == :seconds
-
103
t.since(sign * number)
-
else
-
100
t.advance(type => sign * number)
-
end
-
else
-
1
raise ::ArgumentError, "expected a time or date, got #{time.inspect}"
-
end
-
end
-
end
-
-
1
private
-
-
1
def method_missing(method, *args, &block) #:nodoc:
-
1493
value.send(method, *args, &block)
-
end
-
end
-
end
-
1
module ActiveSupport
-
# FileUpdateChecker specifies the API used by Rails to watch files
-
# and control reloading. The API depends on four methods:
-
#
-
# * +initialize+ which expects two parameters and one block as
-
# described below.
-
#
-
# * +updated?+ which returns a boolean if there were updates in
-
# the filesystem or not.
-
#
-
# * +execute+ which executes the given block on initialization
-
# and updates the latest watched files and timestamp.
-
#
-
# * +execute_if_updated+ which just executes the block if it was updated.
-
#
-
# After initialization, a call to +execute_if_updated+ must execute
-
# the block only if there was really a change in the filesystem.
-
#
-
# This class is used by Rails to reload the I18n framework whenever
-
# they are changed upon a new request.
-
#
-
# i18n_reloader = ActiveSupport::FileUpdateChecker.new(paths) do
-
# I18n.reload!
-
# end
-
#
-
# ActionDispatch::Reloader.to_prepare do
-
# i18n_reloader.execute_if_updated
-
# end
-
1
class FileUpdateChecker
-
# It accepts two parameters on initialization. The first is an array
-
# of files and the second is an optional hash of directories. The hash must
-
# have directories as keys and the value is an array of extensions to be
-
# watched under that directory.
-
#
-
# This method must also receive a block that will be called once a path
-
# changes. The array of files and list of directories cannot be changed
-
# after FileUpdateChecker has been initialized.
-
1
def initialize(files, dirs={}, &block)
-
9
@files = files.freeze
-
9
@glob = compile_glob(dirs)
-
9
@block = block
-
-
9
@watched = nil
-
9
@updated_at = nil
-
-
9
@last_watched = watched
-
9
@last_update_at = updated_at(@last_watched)
-
end
-
-
# Check if any of the entries were updated. If so, the watched and/or
-
# updated_at values are cached until the block is executed via +execute+
-
# or +execute_if_updated+.
-
1
def updated?
-
14
current_watched = watched
-
14
if @last_watched.size != current_watched.size
-
2
@watched = current_watched
-
2
true
-
else
-
12
current_updated_at = updated_at(current_watched)
-
12
if @last_update_at < current_updated_at
-
3
@watched = current_watched
-
3
@updated_at = current_updated_at
-
3
true
-
else
-
9
false
-
end
-
end
-
end
-
-
# Executes the given block and updates the latest watched files and
-
# timestamp.
-
1
def execute
-
5
@last_watched = watched
-
5
@last_update_at = updated_at(@last_watched)
-
5
@block.call
-
ensure
-
5
@watched = nil
-
5
@updated_at = nil
-
end
-
-
# Execute the block given if updated.
-
1
def execute_if_updated
-
11
if updated?
-
4
execute
-
4
true
-
else
-
7
false
-
end
-
end
-
-
1
private
-
-
1
def watched
-
@watched || begin
-
71
all = @files.select { |f| File.exists?(f) }
-
23
all.concat(Dir[@glob]) if @glob
-
23
all
-
28
end
-
end
-
-
1
def updated_at(paths)
-
26
@updated_at || max_mtime(paths) || Time.at(0)
-
end
-
-
# This method returns the maximum mtime of the files in +paths+, or +nil+
-
# if the array is empty.
-
#
-
# Files with a mtime in the future are ignored. Such abnormal situation
-
# can happen for example if the user changes the clock by hand. It is
-
# healthy to consider this edge case because with mtimes in the future
-
# reloading is not triggered.
-
1
def max_mtime(paths)
-
23
time_now = Time.now
-
125
paths.map {|path| File.mtime(path)}.reject {|mtime| time_now < mtime}.max
-
end
-
-
1
def compile_glob(hash)
-
9
hash.freeze # Freeze so changes aren't accidently pushed
-
9
return if hash.empty?
-
-
3
globs = hash.map do |key, value|
-
3
"#{escape(key)}/**/*#{compile_ext(value)}"
-
end
-
3
"{#{globs.join(",")}}"
-
end
-
-
1
def escape(key)
-
3
key.gsub(',','\,')
-
end
-
-
1
def compile_ext(array)
-
3
array = Array(array)
-
3
return if array.empty?
-
3
".{#{array.join(",")}}"
-
end
-
end
-
end
-
1
require 'zlib'
-
1
require 'stringio'
-
-
1
module ActiveSupport
-
# A convenient wrapper for the zlib standard library that allows
-
# compression/decompression of strings with gzip.
-
#
-
# gzip = ActiveSupport::Gzip.compress('compress me!')
-
# # => "\x1F\x8B\b\x00o\x8D\xCDO\x00\x03K\xCE\xCF-(J-.V\xC8MU\x04\x00R>n\x83\f\x00\x00\x00"
-
#
-
# ActiveSupport::Gzip.decompress(gzip)
-
# # => "compress me!"
-
1
module Gzip
-
1
class Stream < StringIO
-
1
def initialize(*)
-
2
super
-
2
set_encoding "BINARY"
-
end
-
3
def close; rewind; end
-
end
-
-
# Decompresses a gzipped string.
-
1
def self.decompress(source)
-
1
Zlib::GzipReader.new(StringIO.new(source)).read
-
end
-
-
# Compresses a string using gzip.
-
1
def self.compress(source)
-
2
output = Stream.new
-
2
gz = Zlib::GzipWriter.new(output)
-
2
gz.write(source)
-
2
gz.close
-
2
output.string
-
end
-
end
-
end
-
1
require 'active_support/core_ext/hash/keys'
-
-
1
module ActiveSupport
-
# Implements a hash where keys <tt>:foo</tt> and <tt>"foo"</tt> are considered
-
# to be the same.
-
#
-
# rgb = ActiveSupport::HashWithIndifferentAccess.new
-
#
-
# rgb[:black] = '#000000'
-
# rgb[:black] # => '#000000'
-
# rgb['black'] # => '#000000'
-
#
-
# rgb['white'] = '#FFFFFF'
-
# rgb[:white] # => '#FFFFFF'
-
# rgb['white'] # => '#FFFFFF'
-
#
-
# Internally symbols are mapped to strings when used as keys in the entire
-
# writing interface (calling <tt>[]=</tt>, <tt>merge</tt>, etc). This
-
# mapping belongs to the public interface. For example, given:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)
-
#
-
# You are guaranteed that the key is returned as a string:
-
#
-
# hash.keys # => ["a"]
-
#
-
# Technically other types of keys are accepted:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)
-
# hash[0] = 0
-
# hash # => {"a"=>1, 0=>0}
-
#
-
# but this class is intended for use cases where strings or symbols are the
-
# expected keys and it is convenient to understand both as the same. For
-
# example the +params+ hash in Ruby on Rails.
-
#
-
# Note that core extensions define <tt>Hash#with_indifferent_access</tt>:
-
#
-
# rgb = { black: '#000000', white: '#FFFFFF' }.with_indifferent_access
-
#
-
# which may be handy.
-
1
class HashWithIndifferentAccess < Hash
-
# Returns +true+ so that <tt>Array#extract_options!</tt> finds members of
-
# this class.
-
1
def extractable_options?
-
1
true
-
end
-
-
1
def with_indifferent_access
-
2
dup
-
end
-
-
1
def nested_under_indifferent_access
-
22
self
-
end
-
-
1
def initialize(constructor = {})
-
219
if constructor.is_a?(Hash)
-
216
super()
-
216
update(constructor)
-
else
-
3
super(constructor)
-
end
-
end
-
-
1
def default(key = nil)
-
147
if key.is_a?(Symbol) && include?(key = key.to_s)
-
52
self[key]
-
else
-
95
super
-
end
-
end
-
-
1
def self.new_from_hash_copying_default(hash)
-
120
new(hash).tap do |new_hash|
-
120
new_hash.default = hash.default
-
end
-
end
-
-
1
def self.[](*args)
-
1
new.merge(Hash[*args])
-
end
-
-
1
alias_method :regular_writer, :[]= unless method_defined?(:regular_writer)
-
1
alias_method :regular_update, :update unless method_defined?(:regular_update)
-
-
# Assigns a new value to the hash:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new
-
# hash[:key] = 'value'
-
#
-
# This value can be later fetched using either +:key+ or +'key'+.
-
1
def []=(key, value)
-
84
regular_writer(convert_key(key), convert_value(value))
-
end
-
-
1
alias_method :store, :[]=
-
-
# Updates the receiver in-place, merging in the hash passed as argument:
-
#
-
# hash_1 = ActiveSupport::HashWithIndifferentAccess.new
-
# hash_1[:key] = 'value'
-
#
-
# hash_2 = ActiveSupport::HashWithIndifferentAccess.new
-
# hash_2[:key] = 'New Value!'
-
#
-
# hash_1.update(hash_2) # => {"key"=>"New Value!"}
-
#
-
# The argument can be either an
-
# <tt>ActiveSupport::HashWithIndifferentAccess</tt> or a regular +Hash+.
-
# In either case the merge respects the semantics of indifferent access.
-
#
-
# If the argument is a regular hash with keys +:key+ and +"key"+ only one
-
# of the values end up in the receiver, but which one is unspecified.
-
#
-
# When given a block, the value for duplicated keys will be determined
-
# by the result of invoking the block with the duplicated key, the value
-
# in the receiver, and the value in +other_hash+. The rules for duplicated
-
# keys follow the semantics of indifferent access:
-
#
-
# hash_1[:key] = 10
-
# hash_2['key'] = 12
-
# hash_1.update(hash_2) { |key, old, new| old + new } # => {"key"=>22}
-
1
def update(other_hash)
-
225
if other_hash.is_a? HashWithIndifferentAccess
-
69
super(other_hash)
-
else
-
156
other_hash.each_pair do |key, value|
-
179
if block_given? && key?(key)
-
2
value = yield(convert_key(key), self[key], value)
-
end
-
179
regular_writer(convert_key(key), convert_value(value))
-
end
-
156
self
-
end
-
end
-
-
1
alias_method :merge!, :update
-
-
# Checks the hash for a key matching the argument passed in:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new
-
# hash['key'] = 'value'
-
# hash.key?(:key) # => true
-
# hash.key?('key') # => true
-
1
def key?(key)
-
102
super(convert_key(key))
-
end
-
-
1
alias_method :include?, :key?
-
1
alias_method :has_key?, :key?
-
1
alias_method :member?, :key?
-
-
# Same as <tt>Hash#fetch</tt> where the key passed as argument can be
-
# either a string or a symbol:
-
#
-
# counters = ActiveSupport::HashWithIndifferentAccess.new
-
# counters[:foo] = 1
-
#
-
# counters.fetch('foo') # => 1
-
# counters.fetch(:bar, 0) # => 0
-
# counters.fetch(:bar) {|key| 0} # => 0
-
# counters.fetch(:zoo) # => KeyError: key not found: "zoo"
-
1
def fetch(key, *extras)
-
9
super(convert_key(key), *extras)
-
end
-
-
# Returns an array of the values at the specified indices:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new
-
# hash[:a] = 'x'
-
# hash[:b] = 'y'
-
# hash.values_at('a', 'b') # => ["x", "y"]
-
1
def values_at(*indices)
-
30
indices.collect {|key| self[convert_key(key)]}
-
end
-
-
# Returns an exact copy of the hash.
-
1
def dup
-
64
self.class.new(self).tap do |new_hash|
-
64
new_hash.default = default
-
end
-
end
-
-
# This method has the same semantics of +update+, except it does not
-
# modify the receiver but rather returns a new hash with indifferent
-
# access with the result of the merge.
-
1
def merge(hash, &block)
-
5
self.dup.update(hash, &block)
-
end
-
-
# Like +merge+ but the other way around: Merges the receiver into the
-
# argument and returns a new hash with indifferent access as result:
-
#
-
# hash = ActiveSupport::HashWithIndifferentAccess.new
-
# hash['a'] = nil
-
# hash.reverse_merge(a: 0, b: 1) # => {"a"=>nil, "b"=>1}
-
1
def reverse_merge(other_hash)
-
1
super(self.class.new_from_hash_copying_default(other_hash))
-
end
-
-
# Same semantics as +reverse_merge+ but modifies the receiver in-place.
-
1
def reverse_merge!(other_hash)
-
1
replace(reverse_merge( other_hash ))
-
end
-
-
# Replaces the contents of this hash with other_hash.
-
#
-
# h = { "a" => 100, "b" => 200 }
-
# h.replace({ "c" => 300, "d" => 400 }) #=> {"c"=>300, "d"=>400}
-
1
def replace(other_hash)
-
4
super(self.class.new_from_hash_copying_default(other_hash))
-
end
-
-
# Removes the specified key from the hash.
-
1
def delete(key)
-
8
super(convert_key(key))
-
end
-
-
5
def stringify_keys!; self end
-
5
def deep_stringify_keys!; self end
-
6
def stringify_keys; dup end
-
6
def deep_stringify_keys; dup end
-
1
undef :symbolize_keys!
-
1
undef :deep_symbolize_keys!
-
8
def symbolize_keys; to_hash.symbolize_keys end
-
8
def deep_symbolize_keys; to_hash.deep_symbolize_keys end
-
2
def to_options!; self end
-
-
# Convert to a regular hash with string keys.
-
1
def to_hash
-
16
Hash.new(default).merge!(self)
-
end
-
-
1
protected
-
1
def convert_key(key)
-
419
key.kind_of?(Symbol) ? key.to_s : key
-
end
-
-
1
def convert_value(value)
-
267
if value.is_a? Hash
-
74
value.nested_under_indifferent_access
-
193
elsif value.is_a?(Array)
-
4
value = value.dup if value.frozen?
-
8
value.map! { |e| convert_value(e) }
-
else
-
189
value
-
end
-
end
-
end
-
end
-
-
1
HashWithIndifferentAccess = ActiveSupport::HashWithIndifferentAccess
-
1
begin
-
1
require 'i18n'
-
1
require 'active_support/lazy_load_hooks'
-
rescue LoadError => e
-
$stderr.puts "The i18n gem is not available. Please add it to your Gemfile and run bundle install"
-
raise e
-
end
-
-
1
ActiveSupport.run_load_hooks(:i18n)
-
1
I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml"
-
1
require 'active_support/inflector/inflections'
-
-
1
module ActiveSupport
-
1
Inflector.inflections(:en) do |inflect|
-
1
inflect.plural(/$/, 's')
-
1
inflect.plural(/s$/i, 's')
-
1
inflect.plural(/^(ax|test)is$/i, '\1es')
-
1
inflect.plural(/(octop|vir)us$/i, '\1i')
-
1
inflect.plural(/(octop|vir)i$/i, '\1i')
-
1
inflect.plural(/(alias|status)$/i, '\1es')
-
1
inflect.plural(/(bu)s$/i, '\1ses')
-
1
inflect.plural(/(buffal|tomat)o$/i, '\1oes')
-
1
inflect.plural(/([ti])um$/i, '\1a')
-
1
inflect.plural(/([ti])a$/i, '\1a')
-
1
inflect.plural(/sis$/i, 'ses')
-
1
inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves')
-
1
inflect.plural(/(hive)$/i, '\1s')
-
1
inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies')
-
1
inflect.plural(/(x|ch|ss|sh)$/i, '\1es')
-
1
inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices')
-
1
inflect.plural(/^(m|l)ouse$/i, '\1ice')
-
1
inflect.plural(/^(m|l)ice$/i, '\1ice')
-
1
inflect.plural(/^(ox)$/i, '\1en')
-
1
inflect.plural(/^(oxen)$/i, '\1')
-
1
inflect.plural(/(quiz)$/i, '\1zes')
-
-
1
inflect.singular(/s$/i, '')
-
1
inflect.singular(/(ss)$/i, '\1')
-
1
inflect.singular(/(n)ews$/i, '\1ews')
-
1
inflect.singular(/([ti])a$/i, '\1um')
-
1
inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '\1sis')
-
1
inflect.singular(/(^analy)(sis|ses)$/i, '\1sis')
-
1
inflect.singular(/([^f])ves$/i, '\1fe')
-
1
inflect.singular(/(hive)s$/i, '\1')
-
1
inflect.singular(/(tive)s$/i, '\1')
-
1
inflect.singular(/([lr])ves$/i, '\1f')
-
1
inflect.singular(/([^aeiouy]|qu)ies$/i, '\1y')
-
1
inflect.singular(/(s)eries$/i, '\1eries')
-
1
inflect.singular(/(m)ovies$/i, '\1ovie')
-
1
inflect.singular(/(x|ch|ss|sh)es$/i, '\1')
-
1
inflect.singular(/^(m|l)ice$/i, '\1ouse')
-
1
inflect.singular(/(bus)(es)?$/i, '\1')
-
1
inflect.singular(/(o)es$/i, '\1')
-
1
inflect.singular(/(shoe)s$/i, '\1')
-
1
inflect.singular(/(cris|test)(is|es)$/i, '\1is')
-
1
inflect.singular(/^(a)x[ie]s$/i, '\1xis')
-
1
inflect.singular(/(octop|vir)(us|i)$/i, '\1us')
-
1
inflect.singular(/(alias|status)(es)?$/i, '\1')
-
1
inflect.singular(/^(ox)en/i, '\1')
-
1
inflect.singular(/(vert|ind)ices$/i, '\1ex')
-
1
inflect.singular(/(matr)ices$/i, '\1ix')
-
1
inflect.singular(/(quiz)zes$/i, '\1')
-
1
inflect.singular(/(database)s$/i, '\1')
-
-
1
inflect.irregular('person', 'people')
-
1
inflect.irregular('man', 'men')
-
1
inflect.irregular('child', 'children')
-
1
inflect.irregular('sex', 'sexes')
-
1
inflect.irregular('move', 'moves')
-
1
inflect.irregular('cow', 'kine')
-
1
inflect.irregular('zombie', 'zombies')
-
-
1
inflect.uncountable(%w(equipment information rice money species series fish sheep jeans police))
-
end
-
end
-
# in case active_support/inflector is required without the rest of active_support
-
1
require 'active_support/inflector/inflections'
-
1
require 'active_support/inflector/transliterate'
-
1
require 'active_support/inflector/methods'
-
-
1
require 'active_support/inflections'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/core_ext/array/prepend_and_append'
-
1
require 'active_support/i18n'
-
-
1
module ActiveSupport
-
1
module Inflector
-
1
extend self
-
-
# A singleton instance of this class is yielded by Inflector.inflections,
-
# which can then be used to specify additional inflection rules. If passed
-
# an optional locale, rules for other languages can be specified. The
-
# default locale is <tt>:en</tt>. Only rules for English are provided.
-
#
-
# ActiveSupport::Inflector.inflections(:en) do |inflect|
-
# inflect.plural /^(ox)$/i, '\1\2en'
-
# inflect.singular /^(ox)en/i, '\1'
-
#
-
# inflect.irregular 'octopus', 'octopi'
-
#
-
# inflect.uncountable 'equipment'
-
# end
-
#
-
# New rules are added at the top. So in the example above, the irregular
-
# rule for octopus will now be the first of the pluralization and
-
# singularization rules that is runs. This guarantees that your rules run
-
# before any of the rules that may already have been loaded.
-
1
class Inflections
-
1
def self.instance(locale = :en)
-
4954
@__instance__ ||= Hash.new { |h, k| h[k] = new }
-
4952
@__instance__[locale]
-
end
-
-
1
attr_reader :plurals, :singulars, :uncountables, :humans, :acronyms, :acronym_regex
-
-
1
def initialize
-
2
@plurals, @singulars, @uncountables, @humans, @acronyms, @acronym_regex = [], [], [], [], {}, /(?=a)b/
-
end
-
-
# Private, for the test suite.
-
1
def initialize_dup(orig) # :nodoc:
-
%w(plurals singulars uncountables humans acronyms acronym_regex).each do |scope|
-
instance_variable_set("@#{scope}", orig.send(scope).dup)
-
end
-
end
-
-
# Specifies a new acronym. An acronym must be specified as it will appear
-
# in a camelized string. An underscore string that contains the acronym
-
# will retain the acronym when passed to +camelize+, +humanize+, or
-
# +titleize+. A camelized string that contains the acronym will maintain
-
# the acronym when titleized or humanized, and will convert the acronym
-
# into a non-delimited single lowercase word when passed to +underscore+.
-
#
-
# acronym 'HTML'
-
# titleize 'html' #=> 'HTML'
-
# camelize 'html' #=> 'HTML'
-
# underscore 'MyHTML' #=> 'my_html'
-
#
-
# The acronym, however, must occur as a delimited unit and not be part of
-
# another word for conversions to recognize it:
-
#
-
# acronym 'HTTP'
-
# camelize 'my_http_delimited' #=> 'MyHTTPDelimited'
-
# camelize 'https' #=> 'Https', not 'HTTPs'
-
# underscore 'HTTPS' #=> 'http_s', not 'https'
-
#
-
# acronym 'HTTPS'
-
# camelize 'https' #=> 'HTTPS'
-
# underscore 'HTTPS' #=> 'https'
-
#
-
# Note: Acronyms that are passed to +pluralize+ will no longer be
-
# recognized, since the acronym will not occur as a delimited unit in the
-
# pluralized result. To work around this, you must specify the pluralized
-
# form as an acronym as well:
-
#
-
# acronym 'API'
-
# camelize(pluralize('api')) #=> 'Apis'
-
#
-
# acronym 'APIs'
-
# camelize(pluralize('api')) #=> 'APIs'
-
#
-
# +acronym+ may be used to specify any word that contains an acronym or
-
# otherwise needs to maintain a non-standard capitalization. The only
-
# restriction is that the word must begin with a capital letter.
-
#
-
# acronym 'RESTful'
-
# underscore 'RESTful' #=> 'restful'
-
# underscore 'RESTfulController' #=> 'restful_controller'
-
# titleize 'RESTfulController' #=> 'RESTful Controller'
-
# camelize 'restful' #=> 'RESTful'
-
# camelize 'restful_controller' #=> 'RESTfulController'
-
#
-
# acronym 'McDonald'
-
# underscore 'McDonald' #=> 'mcdonald'
-
# camelize 'mcdonald' #=> 'McDonald'
-
1
def acronym(word)
-
15
@acronyms[word.downcase] = word
-
15
@acronym_regex = /#{@acronyms.values.join("|")}/
-
end
-
-
# Specifies a new pluralization rule and its replacement. The rule can
-
# either be a string or a regular expression. The replacement should
-
# always be a string that may include references to the matched data from
-
# the rule.
-
1
def plural(rule, replacement)
-
165
@uncountables.delete(rule) if rule.is_a?(String)
-
165
@uncountables.delete(replacement)
-
165
@plurals.prepend([rule, replacement])
-
end
-
-
# Specifies a new singularization rule and its replacement. The rule can
-
# either be a string or a regular expression. The replacement should
-
# always be a string that may include references to the matched data from
-
# the rule.
-
1
def singular(rule, replacement)
-
134
@uncountables.delete(rule) if rule.is_a?(String)
-
134
@uncountables.delete(replacement)
-
134
@singulars.prepend([rule, replacement])
-
end
-
-
# Specifies a new irregular that applies to both pluralization and
-
# singularization at the same time. This can only be used for strings, not
-
# regular expressions. You simply pass the irregular in singular and
-
# plural form.
-
#
-
# irregular 'octopus', 'octopi'
-
# irregular 'person', 'people'
-
1
def irregular(singular, plural)
-
29
@uncountables.delete(singular)
-
29
@uncountables.delete(plural)
-
29
if singular[0,1].upcase == plural[0,1].upcase
-
24
plural(Regexp.new("(#{singular[0,1]})#{singular[1..-1]}$", "i"), '\1' + plural[1..-1])
-
24
plural(Regexp.new("(#{plural[0,1]})#{plural[1..-1]}$", "i"), '\1' + plural[1..-1])
-
24
singular(Regexp.new("(#{plural[0,1]})#{plural[1..-1]}$", "i"), '\1' + singular[1..-1])
-
else
-
5
plural(Regexp.new("#{singular[0,1].upcase}(?i)#{singular[1..-1]}$"), plural[0,1].upcase + plural[1..-1])
-
5
plural(Regexp.new("#{singular[0,1].downcase}(?i)#{singular[1..-1]}$"), plural[0,1].downcase + plural[1..-1])
-
5
plural(Regexp.new("#{plural[0,1].upcase}(?i)#{plural[1..-1]}$"), plural[0,1].upcase + plural[1..-1])
-
5
plural(Regexp.new("#{plural[0,1].downcase}(?i)#{plural[1..-1]}$"), plural[0,1].downcase + plural[1..-1])
-
5
singular(Regexp.new("#{plural[0,1].upcase}(?i)#{plural[1..-1]}$"), singular[0,1].upcase + singular[1..-1])
-
5
singular(Regexp.new("#{plural[0,1].downcase}(?i)#{plural[1..-1]}$"), singular[0,1].downcase + singular[1..-1])
-
end
-
end
-
-
# Add uncountable words that shouldn't be attempted inflected.
-
#
-
# uncountable 'money'
-
# uncountable 'money', 'information'
-
# uncountable %w( money information rice )
-
1
def uncountable(*words)
-
5
(@uncountables << words).flatten!
-
end
-
-
# Specifies a humanized form of a string by a regular expression rule or
-
# by a string mapping. When using a regular expression based replacement,
-
# the normal humanize formatting is called after the replacement. When a
-
# string is used, the human form should be specified as desired (example:
-
# 'The name', not 'the_name').
-
#
-
# human /_cnt$/i, '\1_count'
-
# human 'legacy_col_person_name', 'Name'
-
1
def human(rule, replacement)
-
3
@humans.prepend([rule, replacement])
-
end
-
-
# Clears the loaded inflections within a given scope (default is
-
# <tt>:all</tt>). Give the scope as a symbol of the inflection type, the
-
# options are: <tt>:plurals</tt>, <tt>:singulars</tt>, <tt>:uncountables</tt>,
-
# <tt>:humans</tt>.
-
#
-
# clear :all
-
# clear :plurals
-
1
def clear(scope = :all)
-
3
case scope
-
when :all
-
3
@plurals, @singulars, @uncountables, @humans = [], [], [], []
-
else
-
instance_variable_set "@#{scope}", []
-
end
-
end
-
end
-
-
# Yields a singleton instance of Inflector::Inflections so you can specify
-
# additional inflector rules. If passed an optional locale, rules for other
-
# languages can be specified. If not specified, defaults to <tt>:en</tt>.
-
# Only rules for English are provided.
-
#
-
# ActiveSupport::Inflector.inflections(:en) do |inflect|
-
# inflect.uncountable 'rails'
-
# end
-
1
def inflections(locale = :en)
-
4952
if block_given?
-
37
yield Inflections.instance(locale)
-
else
-
4915
Inflections.instance(locale)
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
require 'active_support/inflector/inflections'
-
1
require 'active_support/inflections'
-
-
1
module ActiveSupport
-
# The Inflector transforms words from singular to plural, class names to table
-
# names, modularized class names to ones without, and class names to foreign
-
# keys. The default inflections for pluralization, singularization, and
-
# uncountable words are kept in inflections.rb.
-
#
-
# The Rails core team has stated patches for the inflections library will not
-
# be accepted in order to avoid breaking legacy applications which may be
-
# relying on errant inflections. If you discover an incorrect inflection and
-
# require it for your application or wish to define rules for languages other
-
# than English, please correct or add them yourself (explained below).
-
1
module Inflector
-
1
extend self
-
-
# Returns the plural form of the word in the string.
-
#
-
# If passed an optional +locale+ parameter, the word will be
-
# pluralized using rules defined for that language. By default,
-
# this parameter is set to <tt>:en</tt>.
-
#
-
# 'post'.pluralize # => "posts"
-
# 'octopus'.pluralize # => "octopi"
-
# 'sheep'.pluralize # => "sheep"
-
# 'words'.pluralize # => "words"
-
# 'CamelOctopus'.pluralize # => "CamelOctopi"
-
# 'ley'.pluralize(:es) # => "leyes"
-
1
def pluralize(word, locale = :en)
-
481
apply_inflections(word, inflections(locale).plurals)
-
end
-
-
# The reverse of +pluralize+, returns the singular form of a word in a
-
# string.
-
#
-
# If passed an optional +locale+ parameter, the word will be
-
# pluralized using rules defined for that language. By default,
-
# this parameter is set to <tt>:en</tt>.
-
#
-
# 'posts'.singularize # => "post"
-
# 'octopi'.singularize # => "octopus"
-
# 'sheep'.singularize # => "sheep"
-
# 'word'.singularize # => "word"
-
# 'CamelOctopi'.singularize # => "CamelOctopus"
-
# 'leyes'.singularize(:es) # => "ley"
-
1
def singularize(word, locale = :en)
-
493
apply_inflections(word, inflections(locale).singulars)
-
end
-
-
# By default, +camelize+ converts strings to UpperCamelCase. If the argument
-
# to +camelize+ is set to <tt>:lower</tt> then +camelize+ produces
-
# lowerCamelCase.
-
#
-
# +camelize+ will also convert '/' to '::' which is useful for converting
-
# paths to namespaces.
-
#
-
# 'active_model'.camelize # => "ActiveModel"
-
# 'active_model'.camelize(:lower) # => "activeModel"
-
# 'active_model/errors'.camelize # => "ActiveModel::Errors"
-
# 'active_model/errors'.camelize(:lower) # => "activeModel::Errors"
-
#
-
# As a rule of thumb you can think of +camelize+ as the inverse of
-
# +underscore+, though there are cases where that does not hold:
-
#
-
# 'SSLError'.underscore.camelize # => "SslError"
-
1
def camelize(term, uppercase_first_letter = true)
-
673
string = term.to_s
-
673
if uppercase_first_letter
-
1304
string = string.sub(/^[a-z\d]*/) { inflections.acronyms[$&] || $&.capitalize }
-
else
-
42
string = string.sub(/^(?:#{inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { $&.downcase }
-
end
-
1663
string.gsub(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" }.gsub('/', '::')
-
end
-
-
# Makes an underscored, lowercase form from the expression in the string.
-
#
-
# Changes '::' to '/' to convert namespaces to paths.
-
#
-
# 'ActiveModel'.underscore # => "active_model"
-
# 'ActiveModel::Errors'.underscore # => "active_model/errors"
-
#
-
# As a rule of thumb you can think of +underscore+ as the inverse of
-
# +camelize+, though there are cases where that does not hold:
-
#
-
# 'SSLError'.underscore.camelize # => "SslError"
-
1
def underscore(camel_cased_word)
-
779
word = camel_cased_word.to_s.dup
-
779
word.gsub!('::', '/')
-
810
word.gsub!(/(?:([A-Za-z\d])|^)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1}#{$1 && '_'}#{$2.downcase}" }
-
779
word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
-
779
word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
-
779
word.tr!("-", "_")
-
779
word.downcase!
-
779
word
-
end
-
-
# Capitalizes the first word and turns underscores into spaces and strips a
-
# trailing "_id", if any. Like +titleize+, this is meant for creating pretty
-
# output.
-
#
-
# 'employee_salary'.humanize # => "Employee salary"
-
# 'author_id'.humanize # => "Author"
-
1
def humanize(lower_case_and_underscored_word)
-
97
result = lower_case_and_underscored_word.to_s.dup
-
212
inflections.humans.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
-
97
result.gsub!(/_id$/, "")
-
97
result.tr!('_', ' ')
-
97
result.gsub(/([a-z\d]*)/i) { |match|
-
422
"#{inflections.acronyms[match] || match.downcase}"
-
95
}.gsub(/^\w/) { $&.upcase }
-
end
-
-
# Capitalizes all the words and replaces some characters in the string to
-
# create a nicer looking title. +titleize+ is meant for creating pretty
-
# output. It is not used in the Rails internals.
-
#
-
# +titleize+ is also aliased as +titlecase+.
-
#
-
# 'man from the boondocks'.titleize # => "Man From The Boondocks"
-
# 'x-men: the last stand'.titleize # => "X Men: The Last Stand"
-
# 'TheManWithoutAPast'.titleize # => "The Man Without A Past"
-
# 'raiders_of_the_lost_ark'.titleize # => "Raiders Of The Lost Ark"
-
1
def titleize(word)
-
131
humanize(underscore(word)).gsub(/\b(?<!['’`])[a-z]/) { $&.capitalize }
-
end
-
-
# Create the name of a table like Rails does for models to table names. This
-
# method uses the +pluralize+ method on the last word in the string.
-
#
-
# 'RawScaledScorer'.tableize # => "raw_scaled_scorers"
-
# 'egg_and_ham'.tableize # => "egg_and_hams"
-
# 'fancyCategory'.tableize # => "fancy_categories"
-
1
def tableize(class_name)
-
4
pluralize(underscore(class_name))
-
end
-
-
# Create a class name from a plural table name like Rails does for table
-
# names to models. Note that this returns a string and not a Class (To
-
# convert to an actual class follow +classify+ with +constantize+).
-
#
-
# 'egg_and_hams'.classify # => "EggAndHam"
-
# 'posts'.classify # => "Post"
-
#
-
# Singular names are not handled correctly:
-
#
-
# 'business'.classify # => "Busines"
-
1
def classify(table_name)
-
# strip out any leading schema name
-
8
camelize(singularize(table_name.to_s.sub(/.*\./, '')))
-
end
-
-
# Replaces underscores with dashes in the string.
-
#
-
# 'puni_puni'.dasherize # => "puni-puni"
-
1
def dasherize(underscored_word)
-
6
underscored_word.tr('_', '-')
-
end
-
-
# Removes the module part from the expression in the string.
-
#
-
# 'ActiveRecord::CoreExtensions::String::Inflections'.demodulize # => "Inflections"
-
# 'Inflections'.demodulize # => "Inflections"
-
#
-
# See also +deconstantize+.
-
1
def demodulize(path)
-
17
path = path.to_s
-
17
if i = path.rindex('::')
-
8
path[(i+2)..-1]
-
else
-
9
path
-
end
-
end
-
-
# Removes the rightmost segment from the constant expression in the string.
-
#
-
# 'Net::HTTP'.deconstantize # => "Net"
-
# '::Net::HTTP'.deconstantize # => "::Net"
-
# 'String'.deconstantize # => ""
-
# '::String'.deconstantize # => ""
-
# ''.deconstantize # => ""
-
#
-
# See also +demodulize+.
-
1
def deconstantize(path)
-
13
path.to_s[0...(path.rindex('::') || 0)] # implementation based on the one in facets' Module#spacename
-
end
-
-
# Creates a foreign key name from a class name.
-
# +separate_class_name_and_id_with_underscore+ sets whether
-
# the method should put '_' between the name and 'id'.
-
#
-
# 'Message'.foreign_key # => "message_id"
-
# 'Message'.foreign_key(false) # => "messageid"
-
# 'Admin::Post'.foreign_key # => "post_id"
-
1
def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
-
8
underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id")
-
end
-
-
# Tries to find a constant with the name specified in the argument string.
-
#
-
# 'Module'.constantize # => Module
-
# 'Test::Unit'.constantize # => Test::Unit
-
#
-
# The name is assumed to be the one of a top-level constant, no matter
-
# whether it starts with "::" or not. No lexical context is taken into
-
# account:
-
#
-
# C = 'outside'
-
# module M
-
# C = 'inside'
-
# C # => 'inside'
-
# 'C'.constantize # => 'outside', same as ::C
-
# end
-
#
-
# NameError is raised when the name is not in CamelCase or the constant is
-
# unknown.
-
1
def constantize(camel_cased_word)
-
593
names = camel_cased_word.split('::')
-
593
names.shift if names.empty? || names.first.empty?
-
-
593
names.inject(Object) do |constant, name|
-
716
if constant == Object
-
559
constant.const_get(name)
-
else
-
157
candidate = constant.const_get(name)
-
145
next candidate if constant.const_defined?(name, false)
-
24
next candidate unless Object.const_defined?(name)
-
-
# Go down the ancestors to check it it's owned
-
# directly before we reach Object or the end of ancestors.
-
20
constant = constant.ancestors.inject do |const, ancestor|
-
16
break const if ancestor == Object
-
12
break ancestor if ancestor.const_defined?(name, false)
-
4
const
-
end
-
-
# owner is in Object, so raise
-
20
constant.const_get(name, false)
-
end
-
end
-
end
-
-
# Tries to find a constant with the name specified in the argument string.
-
#
-
# 'Module'.safe_constantize # => Module
-
# 'Test::Unit'.safe_constantize # => Test::Unit
-
#
-
# The name is assumed to be the one of a top-level constant, no matter
-
# whether it starts with "::" or not. No lexical context is taken into
-
# account:
-
#
-
# C = 'outside'
-
# module M
-
# C = 'inside'
-
# C # => 'inside'
-
# 'C'.safe_constantize # => 'outside', same as ::C
-
# end
-
#
-
# +nil+ is returned when the name is not in CamelCase or the constant (or
-
# part of it) is unknown.
-
#
-
# 'blargle'.safe_constantize # => nil
-
# 'UnknownModule'.safe_constantize # => nil
-
# 'UnknownModule::Foo::Bar'.safe_constantize # => nil
-
1
def safe_constantize(camel_cased_word)
-
56
begin
-
56
constantize(camel_cased_word)
-
25
rescue NameError => e
-
raise unless e.message =~ /(uninitialized constant|wrong constant name) #{const_regexp(camel_cased_word)}$/ ||
-
25
e.name.to_s == camel_cased_word.to_s
-
rescue ArgumentError => e
-
raise unless e.message =~ /not missing constant #{const_regexp(camel_cased_word)}\!$/
-
end
-
end
-
-
# Returns the suffix that should be added to a number to denote the position
-
# in an ordered sequence such as 1st, 2nd, 3rd, 4th.
-
#
-
# ordinal(1) # => "st"
-
# ordinal(2) # => "nd"
-
# ordinal(1002) # => "nd"
-
# ordinal(1003) # => "rd"
-
# ordinal(-11) # => "th"
-
# ordinal(-1021) # => "st"
-
1
def ordinal(number)
-
129
abs_number = number.to_i.abs
-
-
129
if (11..13).include?(abs_number % 100)
-
24
"th"
-
else
-
105
case abs_number % 10
-
21
when 1; "st"
-
12
when 2; "nd"
-
12
when 3; "rd"
-
60
else "th"
-
end
-
end
-
end
-
-
# Turns a number into an ordinal string used to denote the position in an
-
# ordered sequence such as 1st, 2nd, 3rd, 4th.
-
#
-
# ordinalize(1) # => "1st"
-
# ordinalize(2) # => "2nd"
-
# ordinalize(1002) # => "1002nd"
-
# ordinalize(1003) # => "1003rd"
-
# ordinalize(-11) # => "-11th"
-
# ordinalize(-1021) # => "-1021st"
-
1
def ordinalize(number)
-
66
"#{number}#{ordinal(number)}"
-
end
-
-
1
private
-
-
# Mount a regular expression that will match part by part of the constant.
-
# For instance, Foo::Bar::Baz will generate Foo(::Bar(::Baz)?)?
-
1
def const_regexp(camel_cased_word) #:nodoc:
-
25
parts = camel_cased_word.split("::")
-
25
last = parts.pop
-
-
25
parts.reverse.inject(last) do |acc, part|
-
24
part.empty? ? acc : "#{part}(::#{acc})?"
-
end
-
end
-
-
# Applies inflection rules for +singularize+ and +pluralize+.
-
#
-
# apply_inflections('post', inflections.plurals) # => "posts"
-
# apply_inflections('posts', inflections.singulars) # => "post"
-
1
def apply_inflections(word, rules)
-
974
result = word.to_s.dup
-
-
974
if word.empty? || inflections.uncountables.include?(result.downcase[/\b\w+\Z/])
-
142
result
-
else
-
44705
rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
-
832
result
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
1
require 'active_support/core_ext/string/multibyte'
-
1
require 'active_support/i18n'
-
-
1
module ActiveSupport
-
1
module Inflector
-
-
# Replaces non-ASCII characters with an ASCII approximation, or if none
-
# exists, a replacement character which defaults to "?".
-
#
-
# transliterate('Ærøskøbing')
-
# # => "AEroskobing"
-
#
-
# Default approximations are provided for Western/Latin characters,
-
# e.g, "ø", "ñ", "é", "ß", etc.
-
#
-
# This method is I18n aware, so you can set up custom approximations for a
-
# locale. This can be useful, for example, to transliterate German's "ü"
-
# and "ö" to "ue" and "oe", or to add support for transliterating Russian
-
# to ASCII.
-
#
-
# In order to make your custom transliterations available, you must set
-
# them as the <tt>i18n.transliterate.rule</tt> i18n key:
-
#
-
# # Store the transliterations in locales/de.yml
-
# i18n:
-
# transliterate:
-
# rule:
-
# ü: "ue"
-
# ö: "oe"
-
#
-
# # Or set them using Ruby
-
# I18n.backend.store_translations(:de, i18n: {
-
# transliterate: {
-
# rule: {
-
# 'ü' => 'ue',
-
# 'ö' => 'oe'
-
# }
-
# }
-
# })
-
#
-
# The value for <tt>i18n.transliterate.rule</tt> can be a simple Hash that
-
# maps characters to ASCII approximations as shown above, or, for more
-
# complex requirements, a Proc:
-
#
-
# I18n.backend.store_translations(:de, i18n: {
-
# transliterate: {
-
# rule: ->(string) { MyTransliterator.transliterate(string) }
-
# }
-
# })
-
#
-
# Now you can have different transliterations for each locale:
-
#
-
# I18n.locale = :en
-
# transliterate('Jürgen')
-
# # => "Jurgen"
-
#
-
# I18n.locale = :de
-
# transliterate('Jürgen')
-
# # => "Juergen"
-
1
def transliterate(string, replacement = "?")
-
375
I18n.transliterate(ActiveSupport::Multibyte::Unicode.normalize(
-
ActiveSupport::Multibyte::Unicode.tidy_bytes(string), :c),
-
:replacement => replacement)
-
end
-
-
# Replaces special characters in a string so that it may be used as part of
-
# a 'pretty' URL.
-
#
-
# class Person
-
# def to_param
-
# "#{id}-#{name.parameterize}"
-
# end
-
# end
-
#
-
# @person = Person.find(1)
-
# # => #<Person id: 1, name: "Donald E. Knuth">
-
#
-
# <%= link_to(@person.name, person_path(@person)) %>
-
# # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>
-
1
def parameterize(string, sep = '-')
-
# replace accented chars with their ascii equivalents
-
56
parameterized_string = transliterate(string)
-
# Turn unwanted chars into the separator
-
56
parameterized_string.gsub!(/[^a-z0-9\-_]+/i, sep)
-
56
unless sep.nil? || sep.empty?
-
48
re_sep = Regexp.escape(sep)
-
# No more than one of the separator in a row.
-
48
parameterized_string.gsub!(/#{re_sep}{2,}/, sep)
-
# Remove leading/trailing separator.
-
48
parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, '')
-
end
-
56
parameterized_string.downcase
-
end
-
-
end
-
end
-
1
require 'active_support/json/decoding'
-
1
require 'active_support/json/encoding'
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'multi_json'
-
-
1
module ActiveSupport
-
# Look for and parse json strings that look like ISO 8601 times.
-
1
mattr_accessor :parse_json_times
-
-
1
module JSON
-
1
class << self
-
# Parses a JSON string (JavaScript Object Notation) into a hash.
-
# See www.json.org for more info.
-
#
-
# ActiveSupport::JSON.decode("{\"team\":\"rails\",\"players\":\"36\"}")
-
# => {"team" => "rails", "players" => "36"}
-
1
def decode(json, options ={})
-
81
data = MultiJson.load(json, options)
-
80
if ActiveSupport.parse_json_times
-
76
convert_dates_from(data)
-
else
-
4
data
-
end
-
end
-
-
1
def engine
-
78
MultiJson.adapter
-
end
-
1
alias :backend :engine
-
-
1
def engine=(name)
-
156
MultiJson.use(name)
-
end
-
1
alias :backend= :engine=
-
-
1
def with_backend(name)
-
78
old_backend, self.backend = backend, name
-
78
yield
-
ensure
-
78
self.backend = old_backend
-
end
-
-
# Returns the class of the error that will be raised when there is an
-
# error in decoding JSON. Using this method means you won't directly
-
# depend on the ActiveSupport's JSON implementation, in case it changes
-
# in the future.
-
#
-
# begin
-
# obj = ActiveSupport::JSON.decode(some_string)
-
# rescue ActiveSupport::JSON.parse_error
-
# Rails.logger.warn("Attempted to decode invalid JSON: #{some_string}")
-
# end
-
1
def parse_error
-
1
MultiJson::DecodeError
-
end
-
-
1
private
-
-
1
def convert_dates_from(data)
-
200
case data
-
when nil
-
nil
-
when DATE_REGEX
-
26
begin
-
26
DateTime.parse(data)
-
2
rescue ArgumentError
-
2
data
-
end
-
when Array
-
46
data.map! { |d| convert_dates_from(d) }
-
when Hash
-
80
data.each do |key, value|
-
94
data[key] = convert_dates_from(value)
-
end
-
else
-
76
data
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/to_json'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'active_support/json/variable'
-
-
1
require 'bigdecimal'
-
1
require 'active_support/core_ext/big_decimal/conversions' # for #to_s
-
1
require 'active_support/core_ext/hash/except'
-
1
require 'active_support/core_ext/hash/slice'
-
1
require 'active_support/core_ext/object/instance_variables'
-
1
require 'time'
-
1
require 'active_support/core_ext/time/conversions'
-
1
require 'active_support/core_ext/date_time/conversions'
-
1
require 'active_support/core_ext/date/conversions'
-
1
require 'set'
-
-
1
module ActiveSupport
-
1
class << self
-
1
delegate :use_standard_json_time_format, :use_standard_json_time_format=,
-
:escape_html_entities_in_json, :escape_html_entities_in_json=,
-
:encode_big_decimal_as_string, :encode_big_decimal_as_string=,
-
:to => :'ActiveSupport::JSON::Encoding'
-
end
-
-
1
module JSON
-
# matches YAML-formatted dates
-
1
DATE_REGEX = /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[T \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?))$/
-
-
# Dumps objects in JSON (JavaScript Object Notation).
-
# See www.json.org for more info.
-
#
-
# ActiveSupport::JSON.encode({ team: 'rails', players: '36' })
-
# # => "{\"team\":\"rails\",\"players\":\"36\"}"
-
1
def self.encode(value, options = nil)
-
64
Encoding::Encoder.new(options).encode(value)
-
end
-
-
1
module Encoding #:nodoc:
-
1
class CircularReferenceError < StandardError; end
-
-
1
class Encoder
-
1
attr_reader :options
-
-
1
def initialize(options = nil)
-
75
@options = options || {}
-
75
@seen = Set.new
-
end
-
-
1
def encode(value, use_options = true)
-
158
check_for_circular_references(value) do
-
158
jsonified = use_options ? value.as_json(options_for(value)) : value.as_json
-
155
jsonified.encode_json(self)
-
end
-
end
-
-
# like encode, but only calls as_json, without encoding to string.
-
1
def as_json(value, use_options = true)
-
80
check_for_circular_references(value) do
-
77
use_options ? value.as_json(options_for(value)) : value.as_json
-
end
-
end
-
-
1
def options_for(value)
-
179
if value.is_a?(Array) || value.is_a?(Hash)
-
# hashes and arrays need to get encoder in the options, so that
-
# they can detect circular references.
-
42
options.merge(:encoder => self)
-
else
-
137
options
-
end
-
end
-
-
1
def escape(string)
-
106
Encoding.escape(string)
-
end
-
-
1
private
-
1
def check_for_circular_references(value)
-
238
unless @seen.add?(value.__id__)
-
3
raise CircularReferenceError, 'object references itself'
-
end
-
235
yield
-
ensure
-
238
@seen.delete(value.__id__)
-
end
-
end
-
-
-
1
ESCAPED_CHARS = {
-
"\x00" => '\u0000', "\x01" => '\u0001', "\x02" => '\u0002',
-
"\x03" => '\u0003', "\x04" => '\u0004', "\x05" => '\u0005',
-
"\x06" => '\u0006', "\x07" => '\u0007', "\x0B" => '\u000B',
-
"\x0E" => '\u000E', "\x0F" => '\u000F', "\x10" => '\u0010',
-
"\x11" => '\u0011', "\x12" => '\u0012', "\x13" => '\u0013',
-
"\x14" => '\u0014', "\x15" => '\u0015', "\x16" => '\u0016',
-
"\x17" => '\u0017', "\x18" => '\u0018', "\x19" => '\u0019',
-
"\x1A" => '\u001A', "\x1B" => '\u001B', "\x1C" => '\u001C',
-
"\x1D" => '\u001D', "\x1E" => '\u001E', "\x1F" => '\u001F',
-
"\010" => '\b',
-
"\f" => '\f',
-
"\n" => '\n',
-
"\r" => '\r',
-
"\t" => '\t',
-
'"' => '\"',
-
'\\' => '\\\\',
-
'>' => '\u003E',
-
'<' => '\u003C',
-
'&' => '\u0026' }
-
-
1
class << self
-
# If true, use ISO 8601 format for dates and times. Otherwise, fall back
-
# to the Active Support legacy format.
-
1
attr_accessor :use_standard_json_time_format
-
-
# If false, serializes BigDecimal objects as numeric instead of wrapping
-
# them in a string.
-
1
attr_accessor :encode_big_decimal_as_string
-
-
1
attr_accessor :escape_regex
-
1
attr_reader :escape_html_entities_in_json
-
-
1
def escape_html_entities_in_json=(value)
-
39
self.escape_regex = \
-
if @escape_html_entities_in_json = value
-
16
/[\x00-\x1F"\\><&]/
-
else
-
23
/[\x00-\x1F"\\]/
-
end
-
end
-
-
1
def escape(string)
-
106
string = string.encode(::Encoding::UTF_8, :undef => :replace).force_encoding(::Encoding::BINARY)
-
106
json = string.
-
38
gsub(escape_regex) { |s| ESCAPED_CHARS[s] }.
-
gsub(/([\xC0-\xDF][\x80-\xBF]|
-
[\xE0-\xEF][\x80-\xBF]{2}|
-
[\xF0-\xF7][\x80-\xBF]{3})+/nx) { |s|
-
3
s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/n, '\\\\u\&')
-
}
-
106
json = %("#{json}")
-
106
json.force_encoding(::Encoding::UTF_8)
-
106
json
-
end
-
end
-
-
1
self.use_standard_json_time_format = true
-
1
self.escape_html_entities_in_json = true
-
1
self.encode_big_decimal_as_string = true
-
end
-
end
-
end
-
-
1
class Object
-
1
def as_json(options = nil) #:nodoc:
-
2
if respond_to?(:to_hash)
-
1
to_hash
-
else
-
1
instance_values
-
end
-
end
-
end
-
-
1
class Struct #:nodoc:
-
1
def as_json(options = nil)
-
4
Hash[members.zip(values)]
-
end
-
end
-
-
1
class TrueClass
-
1
def as_json(options = nil) #:nodoc:
-
2
self
-
end
-
-
1
def encode_json(encoder) #:nodoc:
-
1
to_s
-
end
-
end
-
-
1
class FalseClass
-
1
def as_json(options = nil) #:nodoc:
-
3
self
-
end
-
-
1
def encode_json(encoder) #:nodoc:
-
2
to_s
-
end
-
end
-
-
1
class NilClass
-
1
def as_json(options = nil) #:nodoc:
-
3
self
-
end
-
-
1
def encode_json(encoder) #:nodoc:
-
6
'null'
-
end
-
end
-
-
1
class String
-
1
def as_json(options = nil) #:nodoc:
-
107
self
-
end
-
-
1
def encode_json(encoder) #:nodoc:
-
106
encoder.escape(self)
-
end
-
end
-
-
1
class Symbol
-
1
def as_json(options = nil) #:nodoc:
-
12
to_s
-
end
-
end
-
-
1
class Numeric
-
1
def as_json(options = nil) #:nodoc:
-
26
self
-
end
-
-
1
def encode_json(encoder) #:nodoc:
-
18
to_s
-
end
-
end
-
-
1
class Float
-
# Encoding Infinity or NaN to JSON should return "null". The default returns
-
# "Infinity" or "NaN" which breaks parsing the JSON. E.g. JSON.parse('[NaN]').
-
1
def as_json(options = nil) #:nodoc:
-
7
finite? ? self : nil
-
end
-
end
-
-
1
class BigDecimal
-
# A BigDecimal would be naturally represented as a JSON number. Most libraries,
-
# however, parse non-integer JSON numbers directly as floats. Clients using
-
# those libraries would get in general a wrong number and no way to recover
-
# other than manually inspecting the string with the JSON code itself.
-
#
-
# That's why a JSON string is returned. The JSON literal is not numeric, but
-
# if the other end knows by contract that the data is supposed to be a
-
# BigDecimal, it still has the chance to post-process the string and get the
-
# real value.
-
#
-
# Use <tt>ActiveSupport.use_standard_json_big_decimal_format = true</tt> to
-
# override this behaviour.
-
1
def as_json(options = nil) #:nodoc:
-
3
if finite?
-
2
ActiveSupport.encode_big_decimal_as_string ? to_s : self
-
else
-
nil
-
end
-
end
-
end
-
-
1
class Regexp
-
1
def as_json(options = nil) #:nodoc:
-
2
to_s
-
end
-
end
-
-
1
module Enumerable
-
1
def as_json(options = nil) #:nodoc:
-
2
to_a.as_json(options)
-
end
-
end
-
-
1
class Range
-
1
def as_json(options = nil) #:nodoc:
-
3
to_s
-
end
-
end
-
-
1
class Array
-
1
def as_json(options = nil) #:nodoc:
-
# use encoder as a proxy to call as_json on all elements, to protect from circular references
-
10
encoder = options && options[:encoder] || ActiveSupport::JSON::Encoding::Encoder.new(options)
-
33
map { |v| encoder.as_json(v, options) }
-
end
-
-
1
def encode_json(encoder) #:nodoc:
-
# we assume here that the encoder has already run as_json on self and the elements, so we run encode_json directly
-
19
"[#{map { |v| v.encode_json(encoder) } * ','}]"
-
end
-
end
-
-
1
class Hash
-
1
def as_json(options = nil) #:nodoc:
-
# create a subset of the hash by applying :only or :except
-
43
subset = if options
-
37
if attrs = options[:only]
-
21
slice(*Array(attrs))
-
elsif attrs = options[:except]
-
1
except(*Array(attrs))
-
else
-
15
self
-
end
-
else
-
6
self
-
end
-
-
# use encoder as a proxy to call as_json on all values in the subset, to protect from circular references
-
43
encoder = options && options[:encoder] || ActiveSupport::JSON::Encoding::Encoder.new(options)
-
100
Hash[subset.map { |k, v| [k.to_s, encoder.as_json(v, options)] }]
-
end
-
-
1
def encode_json(encoder) #:nodoc:
-
# values are encoded with use_options = false, because we don't want hash representations from ActiveModel to be
-
# processed once again with as_json with options, as this could cause unexpected results (i.e. missing fields);
-
-
# on the other hand, we need to run as_json on the elements, because the model representation may contain fields
-
# like Time/Date in their original (not jsonified) form, etc.
-
-
78
"{#{map { |k,v| "#{encoder.encode(k.to_s)}:#{encoder.encode(v, false)}" } * ','}}"
-
end
-
end
-
-
1
class Time
-
1
def as_json(options = nil) #:nodoc:
-
6
if ActiveSupport.use_standard_json_time_format
-
4
xmlschema
-
else
-
2
%(#{strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
-
end
-
end
-
end
-
-
1
class Date
-
1
def as_json(options = nil) #:nodoc:
-
4
if ActiveSupport.use_standard_json_time_format
-
1
strftime("%Y-%m-%d")
-
else
-
3
strftime("%Y/%m/%d")
-
end
-
end
-
end
-
-
1
class DateTime
-
1
def as_json(options = nil) #:nodoc:
-
2
if ActiveSupport.use_standard_json_time_format
-
1
xmlschema
-
else
-
1
strftime('%Y/%m/%d %H:%M:%S %z')
-
end
-
end
-
end
-
1
require 'active_support/deprecation'
-
-
1
module ActiveSupport
-
1
module JSON
-
# Deprecated: A string that returns itself as its JSON-encoded form.
-
1
class Variable < String
-
1
def initialize(*args)
-
2
message = 'ActiveSupport::JSON::Variable is deprecated and will be removed in Rails 4.1. ' \
-
'For your own custom JSON literals, define #as_json and #encode_json yourself.'
-
2
ActiveSupport::Deprecation.warn message
-
2
super
-
end
-
-
1
def as_json(options = nil) self end #:nodoc:
-
1
def encode_json(encoder) self end #:nodoc:
-
end
-
end
-
end
-
1
require 'openssl'
-
-
1
module ActiveSupport
-
# KeyGenerator is a simple wrapper around OpenSSL's implementation of PBKDF2
-
# It can be used to derive a number of keys for various purposes from a given secret.
-
# This lets rails applications have a single secure secret, but avoid reusing that
-
# key in multiple incompatible contexts.
-
1
class KeyGenerator
-
1
def initialize(secret, options = {})
-
2
@secret = secret
-
# The default iterations are higher than required for our key derivation uses
-
# on the off chance someone uses this for password storage
-
2
@iterations = options[:iterations] || 2**16
-
end
-
-
# Returns a derived key suitable for use. The default key_size is chosen
-
# to be compatible with the default settings of ActiveSupport::MessageVerifier.
-
# i.e. OpenSSL::Digest::SHA1#block_length
-
1
def generate_key(salt, key_size=64)
-
2
OpenSSL::PKCS5.pbkdf2_hmac_sha1(@secret, salt, @iterations, key_size)
-
end
-
end
-
end
-
1
module ActiveSupport
-
# lazy_load_hooks allows rails to lazily load a lot of components and thus
-
# making the app boot faster. Because of this feature now there is no need to
-
# require <tt>ActiveRecord::Base</tt> at boot time purely to apply
-
# configuration. Instead a hook is registered that applies configuration once
-
# <tt>ActiveRecord::Base</tt> is loaded. Here <tt>ActiveRecord::Base</tt> is
-
# used as example but this feature can be applied elsewhere too.
-
#
-
# Here is an example where +on_load+ method is called to register a hook.
-
#
-
# initializer 'active_record.initialize_timezone' do
-
# ActiveSupport.on_load(:active_record) do
-
# self.time_zone_aware_attributes = true
-
# self.default_timezone = :utc
-
# end
-
# end
-
#
-
# When the entirety of +activerecord/lib/active_record/base.rb+ has been
-
# evaluated then +run_load_hooks+ is invoked. The very last line of
-
# +activerecord/lib/active_record/base.rb+ is:
-
#
-
# ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)
-
12
@load_hooks = Hash.new { |h,k| h[k] = [] }
-
12
@loaded = Hash.new { |h,k| h[k] = [] }
-
-
1
def self.on_load(name, options = {}, &block)
-
13
@loaded[name].each do |base|
-
8
execute_hook(base, options, block)
-
end
-
-
13
@load_hooks[name] << [block, options]
-
end
-
-
1
def self.execute_hook(base, options, block)
-
16
if options[:yield]
-
2
block.call(base)
-
else
-
14
base.instance_eval(&block)
-
end
-
end
-
-
1
def self.run_load_hooks(name, base = Object)
-
14
@loaded[name] << base
-
14
@load_hooks[name].each do |hook, options|
-
8
execute_hook(base, options, hook)
-
end
-
end
-
end
-
1
require 'active_support/core_ext/module/attribute_accessors'
-
1
require 'active_support/core_ext/class/attribute'
-
-
1
module ActiveSupport
-
# ActiveSupport::LogSubscriber is an object set to consume
-
# ActiveSupport::Notifications with the sole purpose of logging them.
-
# The log subscriber dispatches notifications to a registered object based
-
# on its given namespace.
-
#
-
# An example would be Active Record log subscriber responsible for logging
-
# queries:
-
#
-
# module ActiveRecord
-
# class LogSubscriber < ActiveSupport::LogSubscriber
-
# def sql(event)
-
# "#{event.payload[:name]} (#{event.duration}) #{event.payload[:sql]}"
-
# end
-
# end
-
# end
-
#
-
# And it's finally registered as:
-
#
-
# ActiveRecord::LogSubscriber.attach_to :active_record
-
#
-
# Since we need to know all instance methods before attaching the log
-
# subscriber, the line above should be called after your
-
# <tt>ActiveRecord::LogSubscriber</tt> definition.
-
#
-
# After configured, whenever a "sql.active_record" notification is published,
-
# it will properly dispatch the event (ActiveSupport::Notifications::Event) to
-
# the sql method.
-
#
-
# Log subscriber also has some helpers to deal with logging and automatically
-
# flushes all logs when the request finishes (via action_dispatch.callback
-
# notification) in a Rails environment.
-
1
class LogSubscriber
-
# Embed in a String to clear all previous ANSI sequences.
-
1
CLEAR = "\e[0m"
-
1
BOLD = "\e[1m"
-
-
# Colors
-
1
BLACK = "\e[30m"
-
1
RED = "\e[31m"
-
1
GREEN = "\e[32m"
-
1
YELLOW = "\e[33m"
-
1
BLUE = "\e[34m"
-
1
MAGENTA = "\e[35m"
-
1
CYAN = "\e[36m"
-
1
WHITE = "\e[37m"
-
-
1
mattr_accessor :colorize_logging
-
1
self.colorize_logging = true
-
-
1
class << self
-
1
def logger
-
31
@logger ||= Rails.logger if defined?(Rails)
-
31
@logger
-
end
-
-
1
attr_writer :logger
-
-
1
def attach_to(namespace, log_subscriber=new, notifier=ActiveSupport::Notifications)
-
10
log_subscribers << log_subscriber
-
-
10
log_subscriber.public_methods(false).each do |event|
-
49
next if %w{ start finish }.include?(event.to_s)
-
-
49
notifier.subscribe("#{event}.#{namespace}", log_subscriber)
-
end
-
end
-
-
1
def log_subscribers
-
21
@@log_subscribers ||= []
-
end
-
-
# Flush all log_subscribers' logger.
-
1
def flush_all!
-
2
logger.flush if logger.respond_to?(:flush)
-
end
-
end
-
-
1
def initialize
-
12
@queue_key = [self.class.name, object_id].join "-"
-
12
super
-
end
-
-
1
def logger
-
27
LogSubscriber.logger
-
end
-
-
1
def start(name, id, payload)
-
5
return unless logger
-
-
4
e = ActiveSupport::Notifications::Event.new(name, Time.now, nil, id, payload)
-
4
parent = event_stack.last
-
4
parent << e if parent
-
-
4
event_stack.push e
-
end
-
-
1
def finish(name, id, payload)
-
5
return unless logger
-
-
4
finished = Time.now
-
4
event = event_stack.pop
-
4
event.end = finished
-
4
event.payload.merge!(payload)
-
-
4
method = name.split('.').first
-
4
begin
-
4
send(method, event)
-
1
rescue Exception => e
-
1
logger.error "Could not log #{name.inspect} event. #{e.class}: #{e.message} #{e.backtrace}"
-
end
-
end
-
-
1
protected
-
-
1
%w(info debug warn error fatal unknown).each do |level|
-
6
class_eval <<-METHOD, __FILE__, __LINE__ + 1
-
def #{level}(progname = nil, &block)
-
logger.#{level}(progname, &block) if logger
-
end
-
METHOD
-
end
-
-
# Set color by using a string or one of the defined constants. If a third
-
# option is set to +true+, it also adds bold to the string. This is based
-
# on the Highline implementation and will automatically append CLEAR to the
-
# end of the returned String.
-
1
def color(text, color, bold=false)
-
4
return text unless colorize_logging
-
2
color = self.class.const_get(color.upcase) if color.is_a?(Symbol)
-
2
bold = bold ? BOLD : ""
-
2
"#{bold}#{color}#{text}#{CLEAR}"
-
end
-
-
1
private
-
-
1
def event_stack
-
12
Thread.current[@queue_key] ||= []
-
end
-
end
-
end
-
1
require 'simplecov'
-
1
SimpleCov.start
-
1
require 'active_support/log_subscriber'
-
1
require 'active_support/buffered_logger'
-
1
require 'active_support/notifications'
-
-
1
module ActiveSupport
-
1
class LogSubscriber
-
# Provides some helpers to deal with testing log subscribers by setting up
-
# notifications. Take for instance Active Record subscriber tests:
-
#
-
# class SyncLogSubscriberTest < ActiveSupport::TestCase
-
# include ActiveSupport::LogSubscriber::TestHelper
-
#
-
# def setup
-
# ActiveRecord::LogSubscriber.attach_to(:active_record)
-
# end
-
#
-
# def test_basic_query_logging
-
# Developer.all
-
# wait
-
# assert_equal 1, @logger.logged(:debug).size
-
# assert_match(/Developer Load/, @logger.logged(:debug).last)
-
# assert_match(/SELECT \* FROM "developers"/, @logger.logged(:debug).last)
-
# end
-
# end
-
#
-
# All you need to do is to ensure that your log subscriber is added to
-
# Rails::Subscriber, as in the second line of the code above. The test
-
# helpers are responsible for setting up the queue, subscriptions and
-
# turning colors in logs off.
-
#
-
# The messages are available in the @logger instance, which is a logger with
-
# limited powers (it actually does not send anything to your output), and
-
# you can collect them doing @logger.logged(level), where level is the level
-
# used in logging, like info, debug, warn and so on.
-
1
module TestHelper
-
1
def setup
-
11
@logger = MockLogger.new
-
11
@notifier = ActiveSupport::Notifications::Fanout.new
-
-
11
ActiveSupport::LogSubscriber.colorize_logging = false
-
-
11
@old_notifier = ActiveSupport::Notifications.notifier
-
11
set_logger(@logger)
-
11
ActiveSupport::Notifications.notifier = @notifier
-
end
-
-
1
def teardown
-
11
set_logger(nil)
-
11
ActiveSupport::Notifications.notifier = @old_notifier
-
end
-
-
1
class MockLogger
-
1
include ActiveSupport::Logger::Severity
-
-
1
attr_reader :flush_count
-
1
attr_accessor :level
-
-
1
def initialize(level = DEBUG)
-
17
@flush_count = 0
-
17
@level = level
-
27
@logged = Hash.new { |h,k| h[k] = [] }
-
end
-
-
1
def method_missing(level, message = nil)
-
10
if block_given?
-
1
@logged[level] << yield
-
else
-
9
@logged[level] << message
-
end
-
end
-
-
1
def logged(level)
-
24
@logged[level].compact.map { |l| l.to_s.strip }
-
end
-
-
1
def flush
-
2
@flush_count += 1
-
end
-
-
1
ActiveSupport::Logger::Severity.constants.each do |severity|
-
6
class_eval <<-EOT, __FILE__, __LINE__ + 1
-
def #{severity.downcase}?
-
#{severity} >= @level
-
end
-
EOT
-
end
-
end
-
-
# Wait notifications to be published.
-
1
def wait
-
7
@notifier.wait
-
end
-
-
# Overwrite if you use another logger in your log subscriber.
-
#
-
# def logger
-
# ActiveRecord::Base.logger = @logger
-
# end
-
1
def set_logger(logger)
-
22
ActiveSupport::LogSubscriber.logger = logger
-
end
-
end
-
end
-
end
-
1
require 'logger'
-
-
1
module ActiveSupport
-
1
class Logger < ::Logger
-
# Broadcasts logs to multiple loggers.
-
1
def self.broadcast(logger) # :nodoc:
-
6
Module.new do
-
6
define_method(:add) do |*args, &block|
-
1
logger.add(*args, &block)
-
1
super(*args, &block)
-
end
-
-
6
define_method(:<<) do |x|
-
1
logger << x
-
1
super(x)
-
end
-
-
6
define_method(:close) do
-
1
logger.close
-
1
super()
-
end
-
-
6
define_method(:progname=) do |name|
-
1
logger.progname = name
-
1
super(name)
-
end
-
-
6
define_method(:formatter=) do |formatter|
-
1
logger.formatter = formatter
-
1
super(formatter)
-
end
-
-
6
define_method(:level=) do |level|
-
1
logger.level = level
-
1
super(level)
-
end
-
end
-
end
-
-
1
def initialize(*args)
-
247
super
-
247
@formatter = SimpleFormatter.new
-
end
-
-
# Simple formatter which only displays the message.
-
1
class SimpleFormatter < ::Logger::Formatter
-
# This method is invoked when a log event occurs
-
1
def call(severity, timestamp, progname, msg)
-
388
"#{String === msg ? msg : msg.inspect}\n"
-
end
-
end
-
end
-
end
-
1
require 'base64'
-
1
require 'active_support/core_ext/object/blank'
-
-
1
module ActiveSupport
-
# +MessageVerifier+ makes it easy to generate and verify messages which are
-
# signed to prevent tampering.
-
#
-
# This is useful for cases like remember-me tokens and auto-unsubscribe links
-
# where the session store isn't suitable or available.
-
#
-
# Remember Me:
-
# cookies[:remember_me] = @verifier.generate([@user.id, 2.weeks.from_now])
-
#
-
# In the authentication filter:
-
#
-
# id, time = @verifier.verify(cookies[:remember_me])
-
# if time < Time.now
-
# self.current_user = User.find(id)
-
# end
-
#
-
# By default it uses Marshal to serialize the message. If you want to use
-
# another serialization method, you can set the serializer attribute to
-
# something that responds to dump and load, e.g.:
-
#
-
# @verifier.serializer = YAML
-
1
class MessageVerifier
-
1
class InvalidSignature < StandardError; end
-
-
1
def initialize(secret, options = {})
-
16
@secret = secret
-
16
@digest = options[:digest] || 'SHA1'
-
16
@serializer = options[:serializer] || Marshal
-
end
-
-
1
def verify(signed_message)
-
18
raise InvalidSignature if signed_message.blank?
-
-
16
data, digest = signed_message.split("--")
-
16
if data.present? && digest.present? && secure_compare(digest, generate_digest(data))
-
9
@serializer.load(::Base64.decode64(data))
-
else
-
7
raise InvalidSignature
-
end
-
end
-
-
1
def generate(value)
-
13
data = ::Base64.strict_encode64(@serializer.dump(value))
-
13
"#{data}--#{generate_digest(data)}"
-
end
-
-
1
private
-
# constant-time comparison algorithm to prevent timing attacks
-
1
def secure_compare(a, b)
-
15
return false unless a.bytesize == b.bytesize
-
-
14
l = a.unpack "C#{a.bytesize}"
-
-
14
res = 0
-
574
b.each_byte { |byte| res |= byte ^ l.shift }
-
14
res == 0
-
end
-
-
1
def generate_digest(data)
-
28
require 'openssl' unless defined?(OpenSSL)
-
28
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.const_get(@digest).new, @secret, data)
-
end
-
end
-
end
-
1
module ActiveSupport #:nodoc:
-
1
module Multibyte
-
1
autoload :Chars, 'active_support/multibyte/chars'
-
1
autoload :Unicode, 'active_support/multibyte/unicode'
-
-
# The proxy class returned when calling mb_chars. You can use this accessor
-
# to configure your own proxy class so you can support other encodings. See
-
# the ActiveSupport::Multibyte::Chars implementation for an example how to
-
# do this.
-
#
-
# ActiveSupport::Multibyte.proxy_class = CharsForUTF32
-
1
def self.proxy_class=(klass)
-
@proxy_class = klass
-
end
-
-
# Returns the current proxy class.
-
1
def self.proxy_class
-
265
@proxy_class ||= ActiveSupport::Multibyte::Chars
-
end
-
end
-
end
-
# encoding: utf-8
-
1
require 'active_support/json'
-
1
require 'active_support/core_ext/string/access'
-
1
require 'active_support/core_ext/string/behavior'
-
1
require 'active_support/core_ext/module/delegation'
-
-
1
module ActiveSupport #:nodoc:
-
1
module Multibyte #:nodoc:
-
# Chars enables you to work transparently with UTF-8 encoding in the Ruby
-
# String class without having extensive knowledge about the encoding. A
-
# Chars object accepts a string upon initialization and proxies String
-
# methods in an encoding safe manner. All the normal String methods are also
-
# implemented on the proxy.
-
#
-
# String methods are proxied through the Chars object, and can be accessed
-
# through the +mb_chars+ method. Methods which would normally return a
-
# String object now return a Chars object so methods can be chained.
-
#
-
# 'The Perfect String '.mb_chars.downcase.strip.normalize # => "the perfect string"
-
#
-
# Chars objects are perfectly interchangeable with String objects as long as
-
# no explicit class checks are made. If certain methods do explicitly check
-
# the class, call +to_s+ before you pass chars objects to them.
-
#
-
# bad.explicit_checking_method 'T'.mb_chars.downcase.to_s
-
#
-
# The default Chars implementation assumes that the encoding of the string
-
# is UTF-8, if you want to handle different encodings you can write your own
-
# multibyte string handler and configure it through
-
# ActiveSupport::Multibyte.proxy_class.
-
#
-
# class CharsForUTF32
-
# def size
-
# @wrapped_string.size / 4
-
# end
-
#
-
# def self.accepts?(string)
-
# string.length % 4 == 0
-
# end
-
# end
-
#
-
# ActiveSupport::Multibyte.proxy_class = CharsForUTF32
-
1
class Chars
-
1
include Comparable
-
1
attr_reader :wrapped_string
-
1
alias to_s wrapped_string
-
1
alias to_str wrapped_string
-
-
1
delegate :<=>, :=~, :acts_like_string?, :to => :wrapped_string
-
-
# Creates a new Chars instance by wrapping _string_.
-
1
def initialize(string)
-
792
@wrapped_string = string
-
792
@wrapped_string.force_encoding(Encoding::UTF_8) unless @wrapped_string.frozen?
-
end
-
-
# Forward all undefined methods to the wrapped string.
-
1
def method_missing(method, *args, &block)
-
198
if method.to_s =~ /!$/
-
6
result = @wrapped_string.__send__(method, *args, &block)
-
6
self if result
-
else
-
192
result = @wrapped_string.__send__(method, *args, &block)
-
174
result.kind_of?(String) ? chars(result) : result
-
end
-
end
-
-
# Returns +true+ if _obj_ responds to the given method. Private methods
-
# are included in the search only if the optional second parameter
-
# evaluates to +true+.
-
1
def respond_to_missing?(method, include_private)
-
6
@wrapped_string.respond_to?(method, include_private)
-
end
-
-
# Returns +true+ when the proxy class can handle the string. Returns
-
# +false+ otherwise.
-
1
def self.consumes?(string)
-
123
string.encoding == Encoding::UTF_8
-
end
-
-
# Works just like <tt>String#split</tt>, with the exception that the items
-
# in the resulting list are Chars instances instead of String. This makes
-
# chaining methods easier.
-
#
-
# 'Café périferôl'.mb_chars.split(/é/).map { |part| part.upcase.to_s } # => ["CAF", " P", "RIFERÔL"]
-
1
def split(*args)
-
5
@wrapped_string.split(*args).map { |i| self.class.new(i) }
-
end
-
-
# Works like like <tt>String#slice!</tt>, but returns an instance of
-
# Chars, or nil if the string was not modified.
-
1
def slice!(*args)
-
2
chars(@wrapped_string.slice!(*args))
-
end
-
-
# Reverses all characters in the string.
-
#
-
# 'Café'.mb_chars.reverse.to_s # => 'éfaC'
-
1
def reverse
-
10
chars(Unicode.unpack_graphemes(@wrapped_string).reverse.flatten.pack('U*'))
-
end
-
-
# Limits the byte size of the string to a number of bytes without breaking
-
# characters. Usable when the storage for a string is limited for some
-
# reason.
-
#
-
# 'こんにちは'.mb_chars.limit(7).to_s # => "こん"
-
1
def limit(limit)
-
21
slice(0...translate_offset(limit))
-
end
-
-
# Converts characters in the string to uppercase.
-
#
-
# 'Laurent, où sont les tests ?'.mb_chars.upcase.to_s # => "LAURENT, OÙ SONT LES TESTS ?"
-
1
def upcase
-
15
chars Unicode.upcase(@wrapped_string)
-
end
-
-
# Converts characters in the string to lowercase.
-
#
-
# 'VĚDA A VÝZKUM'.mb_chars.downcase.to_s # => "věda a výzkum"
-
1
def downcase
-
20
chars Unicode.downcase(@wrapped_string)
-
end
-
-
# Converts characters in the string to the opposite case.
-
#
-
# 'El Cañón".mb_chars.swapcase.to_s # => "eL cAÑÓN"
-
1
def swapcase
-
5
chars Unicode.swapcase(@wrapped_string)
-
end
-
-
# Converts the first character to uppercase and the remainder to lowercase.
-
#
-
# 'über'.mb_chars.capitalize.to_s # => "Über"
-
1
def capitalize
-
9
(slice(0) || chars('')).upcase + (slice(1..-1) || chars('')).downcase
-
end
-
-
# Capitalizes the first letter of every word, when possible.
-
#
-
# "ÉL QUE SE ENTERÓ".mb_chars.titleize # => "Él Que Se Enteró"
-
# "日本語".mb_chars.titleize # => "日本語"
-
1
def titleize
-
14
chars(downcase.to_s.gsub(/\b('?\S)/u) { Unicode.upcase($1)})
-
end
-
1
alias_method :titlecase, :titleize
-
-
# Returns the KC normalization of the string by default. NFKC is
-
# considered the best normalization form for passing strings to databases
-
# and validations.
-
#
-
# * <tt>form</tt> - The form you want to normalize in. Should be one of the following:
-
# <tt>:c</tt>, <tt>:kc</tt>, <tt>:d</tt>, or <tt>:kd</tt>. Default is
-
# ActiveSupport::Multibyte::Unicode.default_normalization_form
-
1
def normalize(form = nil)
-
21
chars(Unicode.normalize(@wrapped_string, form))
-
end
-
-
# Performs canonical decomposition on all the characters.
-
#
-
# 'é'.length # => 2
-
# 'é'.mb_chars.decompose.to_s.length # => 3
-
1
def decompose
-
4
chars(Unicode.decompose(:canonical, @wrapped_string.codepoints.to_a).pack('U*'))
-
end
-
-
# Performs composition on all the characters.
-
#
-
# 'é'.length # => 3
-
# 'é'.mb_chars.compose.to_s.length # => 2
-
1
def compose
-
4
chars(Unicode.compose(@wrapped_string.codepoints.to_a).pack('U*'))
-
end
-
-
# Returns the number of grapheme clusters in the string.
-
#
-
# 'क्षि'.mb_chars.length # => 4
-
# 'क्षि'.mb_chars.grapheme_length # => 3
-
1
def grapheme_length
-
19
Unicode.unpack_graphemes(@wrapped_string).length
-
end
-
-
# Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent
-
# resulting in a valid UTF-8 string.
-
#
-
# Passing +true+ will forcibly tidy all bytes, assuming that the string's
-
# encoding is entirely CP1252 or ISO-8859-1.
-
1
def tidy_bytes(force = false)
-
170
chars(Unicode.tidy_bytes(@wrapped_string, force))
-
end
-
-
1
def as_json(options = nil) #:nodoc:
-
1
to_s.as_json(options)
-
end
-
-
1
%w(capitalize downcase reverse tidy_bytes upcase).each do |method|
-
5
define_method("#{method}!") do |*args|
-
7
@wrapped_string = send(method, *args).to_s
-
7
self
-
end
-
end
-
-
1
protected
-
-
1
def translate_offset(byte_offset) #:nodoc:
-
26
return nil if byte_offset.nil?
-
26
return 0 if @wrapped_string == ''
-
-
23
begin
-
30
@wrapped_string.byteslice(0...byte_offset).unpack('U*').length
-
7
rescue ArgumentError
-
7
byte_offset -= 1
-
7
retry
-
end
-
end
-
-
1
def chars(string) #:nodoc:
-
400
self.class.new(string)
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
1
module ActiveSupport
-
1
module Multibyte
-
1
module Unicode
-
-
1
extend self
-
-
# A list of all available normalization forms.
-
# See http://www.unicode.org/reports/tr15/tr15-29.html for more
-
# information about normalization.
-
1
NORMALIZATION_FORMS = [:c, :kc, :d, :kd]
-
-
# The Unicode version that is supported by the implementation
-
1
UNICODE_VERSION = '6.1.0'
-
-
# The default normalization used for operations that require
-
# normalization. It can be set to any of the normalizations
-
# in NORMALIZATION_FORMS.
-
#
-
# ActiveSupport::Multibyte::Unicode.default_normalization_form = :c
-
1
attr_accessor :default_normalization_form
-
1
@default_normalization_form = :kc
-
-
# Hangul character boundaries and properties
-
1
HANGUL_SBASE = 0xAC00
-
1
HANGUL_LBASE = 0x1100
-
1
HANGUL_VBASE = 0x1161
-
1
HANGUL_TBASE = 0x11A7
-
1
HANGUL_LCOUNT = 19
-
1
HANGUL_VCOUNT = 21
-
1
HANGUL_TCOUNT = 28
-
1
HANGUL_NCOUNT = HANGUL_VCOUNT * HANGUL_TCOUNT
-
1
HANGUL_SCOUNT = 11172
-
1
HANGUL_SLAST = HANGUL_SBASE + HANGUL_SCOUNT
-
1
HANGUL_JAMO_FIRST = 0x1100
-
1
HANGUL_JAMO_LAST = 0x11FF
-
-
# All the unicode whitespace
-
1
WHITESPACE = [
-
1
(0x0009..0x000D).to_a, # White_Space # Cc [5] <control-0009>..<control-000D>
-
0x0020, # White_Space # Zs SPACE
-
0x0085, # White_Space # Cc <control-0085>
-
0x00A0, # White_Space # Zs NO-BREAK SPACE
-
0x1680, # White_Space # Zs OGHAM SPACE MARK
-
0x180E, # White_Space # Zs MONGOLIAN VOWEL SEPARATOR
-
1
(0x2000..0x200A).to_a, # White_Space # Zs [11] EN QUAD..HAIR SPACE
-
0x2028, # White_Space # Zl LINE SEPARATOR
-
0x2029, # White_Space # Zp PARAGRAPH SEPARATOR
-
0x202F, # White_Space # Zs NARROW NO-BREAK SPACE
-
0x205F, # White_Space # Zs MEDIUM MATHEMATICAL SPACE
-
0x3000, # White_Space # Zs IDEOGRAPHIC SPACE
-
].flatten.freeze
-
-
# BOM (byte order mark) can also be seen as whitespace, it's a
-
# non-rendering character used to distinguish between little and big
-
# endian. This is not an issue in utf-8, so it must be ignored.
-
1
LEADERS_AND_TRAILERS = WHITESPACE + [65279] # ZERO-WIDTH NO-BREAK SPACE aka BOM
-
-
# Returns a regular expression pattern that matches the passed Unicode
-
# codepoints.
-
1
def self.codepoints_to_pattern(array_of_codepoints) #:nodoc:
-
56
array_of_codepoints.collect{ |e| [e].pack 'U*' }.join('|')
-
end
-
1
TRAILERS_PAT = /(#{codepoints_to_pattern(LEADERS_AND_TRAILERS)})+\Z/u
-
1
LEADERS_PAT = /\A(#{codepoints_to_pattern(LEADERS_AND_TRAILERS)})+/u
-
-
# Detect whether the codepoint is in a certain character class. Returns
-
# +true+ when it's in the specified character class and +false+ otherwise.
-
# Valid character classes are: <tt>:cr</tt>, <tt>:lf</tt>, <tt>:l</tt>,
-
# <tt>:v</tt>, <tt>:lv</tt>, <tt>:lvt</tt> and <tt>:t</tt>.
-
#
-
# Primarily used by the grapheme cluster support.
-
1
def in_char_class?(codepoint, classes)
-
537
classes.detect { |c| database.boundary[c] === codepoint } ? true : false
-
end
-
-
# Unpack the string at grapheme boundaries. Returns a list of character
-
# lists.
-
#
-
# Unicode.unpack_graphemes('क्षि') # => [[2325, 2381], [2359], [2367]]
-
# Unicode.unpack_graphemes('Café') # => [[67], [97], [102], [233]]
-
1
def unpack_graphemes(string)
-
29
codepoints = string.codepoints.to_a
-
29
unpacked = []
-
29
pos = 0
-
29
marker = 0
-
29
eoc = codepoints.length
-
150
while(pos < eoc)
-
92
pos += 1
-
92
previous = codepoints[pos-1]
-
92
current = codepoints[pos]
-
if (
-
# CR X LF
-
( previous == database.boundary[:cr] and current == database.boundary[:lf] ) or
-
# L X (L|V|LV|LVT)
-
92
( database.boundary[:l] === previous and in_char_class?(current, [:l,:v,:lv,:lvt]) ) or
-
# (LV|V) X (V|T)
-
( in_char_class?(previous, [:lv,:v]) and in_char_class?(current, [:v,:t]) ) or
-
# (LVT|T) X (T)
-
( in_char_class?(previous, [:lvt,:t]) and database.boundary[:t] === current ) or
-
# X Extend
-
78
(database.boundary[:extend] === current)
-
)
-
else
-
73
unpacked << codepoints[marker..pos-1]
-
73
marker = pos
-
end
-
end
-
29
unpacked
-
end
-
-
# Reverse operation of unpack_graphemes.
-
#
-
# Unicode.pack_graphemes(Unicode.unpack_graphemes('क्षि')) # => 'क्षि'
-
1
def pack_graphemes(unpacked)
-
unpacked.flatten.pack('U*')
-
end
-
-
# Re-order codepoints so the string becomes canonical.
-
1
def reorder_characters(codepoints)
-
396
length = codepoints.length- 1
-
396
pos = 0
-
396
while pos < length do
-
67152
cp1, cp2 = database.codepoints[codepoints[pos]], database.codepoints[codepoints[pos+1]]
-
67152
if (cp1.combining_class > cp2.combining_class) && (cp2.combining_class > 0)
-
codepoints[pos..pos+1] = cp2.code, cp1.code
-
pos += (pos > 0 ? -1 : 1)
-
else
-
67152
pos += 1
-
end
-
end
-
396
codepoints
-
end
-
-
# Decompose composed characters to the decomposed form.
-
1
def decompose(type, codepoints)
-
30852
codepoints.inject([]) do |decomposed, cp|
-
# if it's a hangul syllable starter character
-
98015
if HANGUL_SBASE <= cp and cp < HANGUL_SLAST
-
sindex = cp - HANGUL_SBASE
-
ncp = [] # new codepoints
-
ncp << HANGUL_LBASE + sindex / HANGUL_NCOUNT
-
ncp << HANGUL_VBASE + (sindex % HANGUL_NCOUNT) / HANGUL_TCOUNT
-
tindex = sindex % HANGUL_TCOUNT
-
ncp << (HANGUL_TBASE + tindex) unless tindex == 0
-
decomposed.concat ncp
-
# if the codepoint is decomposable in with the current decomposition type
-
98015
elsif (ncp = database.codepoints[cp].decomp_mapping) and (!database.codepoints[cp].decomp_type || type == :compatability)
-
30452
decomposed.concat decompose(type, ncp.dup)
-
else
-
67563
decomposed << cp
-
end
-
end
-
end
-
-
# Compose decomposed characters to the composed form.
-
1
def compose(codepoints)
-
392
pos = 0
-
392
eoa = codepoints.length - 1
-
392
starter_pos = 0
-
392
starter_char = codepoints[0]
-
392
previous_combining_class = -1
-
392
while pos < eoa
-
67125
pos += 1
-
67125
lindex = starter_char - HANGUL_LBASE
-
# -- Hangul
-
67125
if 0 <= lindex and lindex < HANGUL_LCOUNT
-
1
vindex = codepoints[starter_pos+1] - HANGUL_VBASE rescue vindex = -1
-
1
if 0 <= vindex and vindex < HANGUL_VCOUNT
-
tindex = codepoints[starter_pos+2] - HANGUL_TBASE rescue tindex = -1
-
if 0 <= tindex and tindex < HANGUL_TCOUNT
-
j = starter_pos + 2
-
eoa -= 2
-
else
-
tindex = 0
-
j = starter_pos + 1
-
eoa -= 1
-
end
-
codepoints[starter_pos..j] = (lindex * HANGUL_VCOUNT + vindex) * HANGUL_TCOUNT + tindex + HANGUL_SBASE
-
end
-
1
starter_pos += 1
-
1
starter_char = codepoints[starter_pos]
-
# -- Other characters
-
else
-
67124
current_char = codepoints[pos]
-
67124
current = database.codepoints[current_char]
-
67124
if current.combining_class > previous_combining_class
-
60759
if ref = database.composition_map[starter_char]
-
36933
composition = ref[current_char]
-
else
-
23826
composition = nil
-
end
-
60759
unless composition.nil?
-
30441
codepoints[starter_pos] = composition
-
30441
starter_char = composition
-
30441
codepoints.delete_at pos
-
30441
eoa -= 1
-
30441
pos -= 1
-
30441
previous_combining_class = -1
-
else
-
30318
previous_combining_class = current.combining_class
-
end
-
else
-
6365
previous_combining_class = current.combining_class
-
end
-
67124
if current.combining_class == 0
-
36681
starter_pos = pos
-
36681
starter_char = codepoints[pos]
-
end
-
end
-
end
-
392
codepoints
-
end
-
-
# Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent
-
# resulting in a valid UTF-8 string.
-
#
-
# Passing +true+ will forcibly tidy all bytes, assuming that the string's
-
# encoding is entirely CP1252 or ISO-8859-1.
-
1
def tidy_bytes(string, force = false)
-
545
if force
-
return string.unpack("C*").map do |b|
-
4
tidy_byte(b)
-
1
end.flatten.compact.pack("C*").unpack("U*").pack("U*")
-
end
-
-
544
bytes = string.unpack("C*")
-
544
conts_expected = 0
-
544
last_lead = 0
-
-
544
bytes.each_index do |i|
-
-
73226
byte = bytes[i]
-
73226
is_cont = byte > 127 && byte < 192
-
73226
is_lead = byte > 191 && byte < 245
-
73226
is_unused = byte > 240
-
73226
is_restricted = byte > 244
-
-
# Impossible or highly unlikely byte? Clean it.
-
73226
if is_unused || is_restricted
-
24
bytes[i] = tidy_byte(byte)
-
elsif is_cont
-
# Not expecting continuation byte? Clean up. Otherwise, now expect one less.
-
35873
conts_expected == 0 ? bytes[i] = tidy_byte(byte) : conts_expected -= 1
-
else
-
37329
if conts_expected > 0
-
# Expected continuation, but got ASCII or leading? Clean backwards up to
-
# the leading byte.
-
130
(1..(i - last_lead)).each {|j| bytes[i - j] = tidy_byte(bytes[i - j])}
-
64
conts_expected = 0
-
end
-
37329
if is_lead
-
# Final byte is leading? Clean it.
-
35920
if i == bytes.length - 1
-
46
bytes[i] = tidy_byte(bytes.last)
-
else
-
# Valid leading byte? Expect continuations determined by position of
-
# first zero bit, with max of 3.
-
35874
conts_expected = byte < 224 ? 1 : byte < 240 ? 2 : 3
-
35874
last_lead = i
-
end
-
end
-
end
-
end
-
544
bytes.empty? ? "" : bytes.flatten.compact.pack("C*").unpack("U*").pack("U*")
-
end
-
-
# Returns the KC normalization of the string by default. NFKC is
-
# considered the best normalization form for passing strings to databases
-
# and validations.
-
#
-
# * <tt>string</tt> - The string to perform normalization on.
-
# * <tt>form</tt> - The form you want to normalize in. Should be one of
-
# the following: <tt>:c</tt>, <tt>:kc</tt>, <tt>:d</tt>, or <tt>:kd</tt>.
-
# Default is ActiveSupport::Multibyte.default_normalization_form.
-
1
def normalize(string, form=nil)
-
396
form ||= @default_normalization_form
-
# See http://www.unicode.org/reports/tr15, Table 1
-
396
codepoints = string.codepoints.to_a
-
396
case form
-
when :d
-
4
reorder_characters(decompose(:canonical, codepoints))
-
when :c
-
382
compose(reorder_characters(decompose(:canonical, codepoints)))
-
when :kd
-
4
reorder_characters(decompose(:compatability, codepoints))
-
when :kc
-
6
compose(reorder_characters(decompose(:compatability, codepoints)))
-
else
-
raise ArgumentError, "#{form} is not a valid normalization variant", caller
-
end.pack('U*')
-
end
-
-
1
def downcase(string)
-
20
apply_mapping string, :lowercase_mapping
-
end
-
-
1
def upcase(string)
-
24
apply_mapping string, :uppercase_mapping
-
end
-
-
1
def swapcase(string)
-
5
apply_mapping string, :swapcase_mapping
-
end
-
-
# Holds data about a codepoint in the Unicode database.
-
1
class Codepoint
-
1
attr_accessor :code, :combining_class, :decomp_type, :decomp_mapping, :uppercase_mapping, :lowercase_mapping
-
-
1
def swapcase_mapping
-
13
uppercase_mapping > 0 ? uppercase_mapping : lowercase_mapping
-
end
-
end
-
-
# Holds static data from the Unicode database.
-
1
class UnicodeDatabase
-
1
ATTRIBUTES = :codepoints, :composition_exclusion, :composition_map, :boundary, :cp1252
-
-
1
attr_writer(*ATTRIBUTES)
-
-
1
def initialize
-
7
@codepoints = Hash.new(Codepoint.new)
-
7
@composition_exclusion = []
-
7
@composition_map = {}
-
7
@boundary = {}
-
7
@cp1252 = {}
-
end
-
-
# Lazy load the Unicode database so it's only loaded when it's actually used
-
1
ATTRIBUTES.each do |attr_name|
-
5
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
-
def #{attr_name} # def codepoints
-
load # load
-
@#{attr_name} # @codepoints
-
end # end
-
EOS
-
end
-
-
# Loads the Unicode database and returns all the internal objects of
-
# UnicodeDatabase.
-
1
def load
-
2
begin
-
4
@codepoints, @composition_exclusion, @composition_map, @boundary, @cp1252 = File.open(self.class.filename, 'rb') { |f| Marshal.load f.read }
-
rescue => e
-
raise IOError.new("Couldn't load the Unicode tables for UTF8Handler (#{e.message}), ActiveSupport::Multibyte is unusable")
-
end
-
-
# Redefine the === method so we can write shorter rules for grapheme cluster breaks
-
2
@boundary.each do |k,_|
-
@boundary[k].instance_eval do
-
16
def ===(other)
-
83775
detect { |i| i === other } ? true : false
-
end
-
20
end if @boundary[k].kind_of?(Array)
-
end
-
-
# define attr_reader methods for the instance variables
-
2
class << self
-
2
attr_reader(*ATTRIBUTES)
-
end
-
end
-
-
# Returns the directory in which the data files are stored.
-
1
def self.dirname
-
2
File.dirname(__FILE__) + '/../values/'
-
end
-
-
# Returns the filename for the data file for this version.
-
1
def self.filename
-
2
File.expand_path File.join(dirname, "unicode_tables.dat")
-
end
-
end
-
-
1
private
-
-
1
def apply_mapping(string, mapping) #:nodoc:
-
49
string.each_codepoint.map do |codepoint|
-
189
cp = database.codepoints[codepoint]
-
189
if cp and (ncp = cp.send(mapping)) and ncp > 0
-
79
ncp
-
else
-
110
codepoint
-
end
-
end.pack('U*')
-
end
-
-
1
def tidy_byte(byte)
-
191
if byte < 160
-
41
[database.cp1252[byte] || byte].pack("U").unpack("C*")
-
150
elsif byte < 192
-
15
[194, byte]
-
else
-
135
[195, byte - 64]
-
end
-
end
-
-
1
def database
-
392458
@database ||= UnicodeDatabase.new
-
end
-
-
end
-
end
-
end
-
1
require 'active_support/notifications/instrumenter'
-
1
require 'active_support/notifications/fanout'
-
-
1
module ActiveSupport
-
# = Notifications
-
#
-
# <tt>ActiveSupport::Notifications</tt> provides an instrumentation API for
-
# Ruby.
-
#
-
# == Instrumenters
-
#
-
# To instrument an event you just need to do:
-
#
-
# ActiveSupport::Notifications.instrument('render', extra: :information) do
-
# render text: 'Foo'
-
# end
-
#
-
# That executes the block first and notifies all subscribers once done.
-
#
-
# In the example above +render+ is the name of the event, and the rest is called
-
# the _payload_. The payload is a mechanism that allows instrumenters to pass
-
# extra information to subscribers. Payloads consist of a hash whose contents
-
# are arbitrary and generally depend on the event.
-
#
-
# == Subscribers
-
#
-
# You can consume those events and the information they provide by registering
-
# a subscriber.
-
#
-
# ActiveSupport::Notifications.subscribe('render') do |name, start, finish, id, payload|
-
# name # => String, name of the event (such as 'render' from above)
-
# start # => Time, when the instrumented block started execution
-
# finish # => Time, when the instrumented block ended execution
-
# id # => String, unique ID for this notification
-
# payload # => Hash, the payload
-
# end
-
#
-
# For instance, let's store all "render" events in an array:
-
#
-
# events = []
-
#
-
# ActiveSupport::Notifications.subscribe('render') do |*args|
-
# events << ActiveSupport::Notifications::Event.new(*args)
-
# end
-
#
-
# That code returns right away, you are just subscribing to "render" events.
-
# The block is saved and will be called whenever someone instruments "render":
-
#
-
# ActiveSupport::Notifications.instrument('render', extra: :information) do
-
# render text: 'Foo'
-
# end
-
#
-
# event = events.first
-
# event.name # => "render"
-
# event.duration # => 10 (in milliseconds)
-
# event.payload # => { extra: :information }
-
#
-
# The block in the <tt>subscribe</tt> call gets the name of the event, start
-
# timestamp, end timestamp, a string with a unique identifier for that event
-
# (something like "535801666f04d0298cd6"), and a hash with the payload, in
-
# that order.
-
#
-
# If an exception happens during that particular instrumentation the payload will
-
# have a key <tt>:exception</tt> with an array of two elements as value: a string with
-
# the name of the exception class, and the exception message.
-
#
-
# As the previous example depicts, the class <tt>ActiveSupport::Notifications::Event</tt>
-
# is able to take the arguments as they come and provide an object-oriented
-
# interface to that data.
-
#
-
# It is also possible to pass an object as the second parameter passed to the
-
# <tt>subscribe</tt> method instead of a block:
-
#
-
# module ActionController
-
# class PageRequest
-
# def call(name, started, finished, unique_id, payload)
-
# Rails.logger.debug ['notification:', name, started, finished, unique_id, payload].join(' ')
-
# end
-
# end
-
# end
-
#
-
# ActiveSupport::Notifications.subscribe('process_action.action_controller', ActionController::PageRequest.new)
-
#
-
# resulting in the following output within the logs including a hash with the payload:
-
#
-
# notification: process_action.action_controller 2012-04-13 01:08:35 +0300 2012-04-13 01:08:35 +0300 af358ed7fab884532ec7 {
-
# :controller=>"Devise::SessionsController",
-
# :action=>"new",
-
# :params=>{"action"=>"new", "controller"=>"devise/sessions"},
-
# :format=>:html,
-
# :method=>"GET",
-
# :path=>"/login/sign_in",
-
# :status=>200,
-
# :view_runtime=>279.3080806732178,
-
# :db_runtime=>40.053
-
# }
-
#
-
# You can also subscribe to all events whose name matches a certain regexp:
-
#
-
# ActiveSupport::Notifications.subscribe(/render/) do |*args|
-
# ...
-
# end
-
#
-
# and even pass no argument to <tt>subscribe</tt>, in which case you are subscribing
-
# to all events.
-
#
-
# == Temporary Subscriptions
-
#
-
# Sometimes you do not want to subscribe to an event for the entire life of
-
# the application. There are two ways to unsubscribe.
-
#
-
# WARNING: The instrumentation framework is designed for long-running subscribers,
-
# use this feature sparingly because it wipes some internal caches and that has
-
# a negative impact on performance.
-
#
-
# === Subscribe While a Block Runs
-
#
-
# You can subscribe to some event temporarily while some block runs. For
-
# example, in
-
#
-
# callback = lambda {|*args| ... }
-
# ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do
-
# ...
-
# end
-
#
-
# the callback will be called for all "sql.active_record" events instrumented
-
# during the execution of the block. The callback is unsubscribed automatically
-
# after that.
-
#
-
# === Manual Unsubscription
-
#
-
# The +subscribe+ method returns a subscriber object:
-
#
-
# subscriber = ActiveSupport::Notifications.subscribe("render") do |*args|
-
# ...
-
# end
-
#
-
# To prevent that block from being called anymore, just unsubscribe passing
-
# that reference:
-
#
-
# ActiveSupport::Notifications.unsubscribe(subscriber)
-
#
-
# == Default Queue
-
#
-
# Notifications ships with a queue implementation that consumes and publish events
-
# to log subscribers in a thread. You can use any queue implementation you want.
-
#
-
1
module Notifications
-
1
class << self
-
1
attr_accessor :notifier
-
-
1
def publish(name, *args)
-
notifier.publish(name, *args)
-
end
-
-
1
def instrument(name, payload = {})
-
17
if notifier.listening?(name)
-
30
instrumenter.instrument(name, payload) { yield payload if block_given? }
-
else
-
2
yield payload if block_given?
-
end
-
end
-
-
1
def subscribe(*args, &block)
-
51
notifier.subscribe(*args, &block)
-
end
-
-
1
def subscribed(callback, *args, &block)
-
1
subscriber = subscribe(*args, &callback)
-
1
yield
-
ensure
-
1
unsubscribe(subscriber)
-
end
-
-
1
def unsubscribe(args)
-
1
notifier.unsubscribe(args)
-
end
-
-
1
def instrumenter
-
16
Thread.current[:"instrumentation_#{notifier.object_id}"] ||= Instrumenter.new(notifier)
-
end
-
end
-
-
1
self.notifier = Fanout.new
-
end
-
end
-
1
require 'mutex_m'
-
-
1
module ActiveSupport
-
1
module Notifications
-
# This is a default queue implementation that ships with Notifications.
-
# It just pushes events to all registered log subscribers.
-
#
-
# This class is thread safe. All methods are reentrant.
-
1
class Fanout
-
1
include Mutex_m
-
-
1
def initialize
-
35
@subscribers = []
-
35
@listeners_for = {}
-
35
super
-
end
-
-
1
def subscribe(pattern = nil, block = Proc.new)
-
97
subscriber = Subscribers.new pattern, block
-
97
synchronize do
-
97
@subscribers << subscriber
-
97
@listeners_for.clear
-
end
-
97
subscriber
-
end
-
-
1
def unsubscribe(subscriber)
-
4
synchronize do
-
13
@subscribers.reject! { |s| s.matches?(subscriber) }
-
4
@listeners_for.clear
-
end
-
end
-
-
1
def start(name, id, payload)
-
43
listeners_for(name).each { |s| s.start(name, id, payload) }
-
end
-
-
1
def finish(name, id, payload)
-
42
listeners_for(name).each { |s| s.finish(name, id, payload) }
-
end
-
-
1
def publish(name, *args)
-
46
listeners_for(name).each { |s| s.publish(name, *args) }
-
end
-
-
1
def listeners_for(name)
-
78
synchronize do
-
177
@listeners_for[name] ||= @subscribers.select { |s| s.subscribed_to?(name) }
-
end
-
end
-
-
1
def listening?(name)
-
17
listeners_for(name).any?
-
end
-
-
# This is a sync queue, so there is no waiting.
-
1
def wait
-
end
-
-
1
module Subscribers # :nodoc:
-
1
def self.new(pattern, listener)
-
97
if listener.respond_to?(:start) and listener.respond_to?(:finish)
-
54
subscriber = Evented.new pattern, listener
-
else
-
43
subscriber = Timed.new pattern, listener
-
end
-
-
97
unless pattern
-
21
AllMessages.new(subscriber)
-
else
-
76
subscriber
-
end
-
end
-
-
1
class Evented #:nodoc:
-
1
def initialize(pattern, delegate)
-
97
@pattern = pattern
-
97
@delegate = delegate
-
end
-
-
1
def start(name, id, payload)
-
10
@delegate.start name, id, payload
-
end
-
-
1
def finish(name, id, payload)
-
10
@delegate.finish name, id, payload
-
end
-
-
1
def subscribed_to?(name)
-
71
@pattern === name.to_s
-
end
-
-
1
def matches?(subscriber_or_name)
-
self === subscriber_or_name ||
-
5
@pattern && @pattern === subscriber_or_name
-
end
-
end
-
-
1
class Timed < Evented
-
1
def initialize(pattern, delegate)
-
43
@timestack = []
-
43
super
-
end
-
-
1
def publish(name, *args)
-
26
@delegate.call name, *args
-
end
-
-
1
def start(name, id, payload)
-
12
@timestack.push Time.now
-
end
-
-
1
def finish(name, id, payload)
-
12
started = @timestack.pop
-
12
@delegate.call(name, started, Time.now, id, payload)
-
end
-
end
-
-
1
class AllMessages # :nodoc:
-
1
def initialize(delegate)
-
21
@delegate = delegate
-
end
-
-
1
def start(name, id, payload)
-
12
@delegate.start name, id, payload
-
end
-
-
1
def finish(name, id, payload)
-
12
@delegate.finish name, id, payload
-
end
-
-
1
def publish(name, *args)
-
20
@delegate.publish name, *args
-
end
-
-
1
def subscribed_to?(name)
-
28
true
-
end
-
-
1
alias :matches? :===
-
end
-
end
-
end
-
end
-
end
-
1
require 'securerandom'
-
-
1
module ActiveSupport
-
1
module Notifications
-
# Instrumentors are stored in a thread local.
-
1
class Instrumenter
-
1
attr_reader :id
-
-
1
def initialize(notifier)
-
11
@id = unique_id
-
11
@notifier = notifier
-
end
-
-
# Instrument the given block by measuring the time taken to execute it
-
# and publish it. Notice that events get sent even if an error occurs
-
# in the passed-in block.
-
1
def instrument(name, payload={})
-
15
@notifier.start(name, @id, payload)
-
15
begin
-
15
yield
-
1
rescue Exception => e
-
1
payload[:exception] = [e.class.name, e.message]
-
1
raise e
-
ensure
-
15
@notifier.finish(name, @id, payload)
-
15
end
-
end
-
-
1
private
-
1
def unique_id
-
11
SecureRandom.hex(10)
-
end
-
end
-
-
1
class Event
-
1
attr_reader :name, :time, :transaction_id, :payload, :children
-
1
attr_accessor :end
-
-
1
def initialize(name, start, ending, transaction_id, payload)
-
19
@name = name
-
19
@payload = payload.dup
-
19
@time = start
-
19
@transaction_id = transaction_id
-
19
@end = ending
-
19
@children = []
-
end
-
-
1
def duration
-
1
1000.0 * (self.end - time)
-
end
-
-
1
def <<(event)
-
@children << event
-
end
-
-
1
def parent_of?(event)
-
4
@children.include? event
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/big_decimal/conversions'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/core_ext/hash/keys'
-
1
require 'active_support/i18n'
-
-
1
module ActiveSupport
-
1
module NumberHelper
-
1
extend self
-
-
1
DEFAULTS = {
-
# Used in number_to_delimited
-
# These are also the defaults for 'currency', 'percentage', 'precision', and 'human'
-
format: {
-
# Sets the separator between the units, for more precision (e.g. 1.0 / 2.0 == 0.5)
-
separator: ".",
-
# Delimits thousands (e.g. 1,000,000 is a million) (always in groups of three)
-
delimiter: ",",
-
# Number of decimals, behind the separator (the number 1 with a precision of 2 gives: 1.00)
-
precision: 3,
-
# If set to true, precision will mean the number of significant digits instead
-
# of the number of decimal digits (1234 with precision 2 becomes 1200, 1.23543 becomes 1.2)
-
significant: false,
-
# If set, the zeros after the decimal separator will always be stripped (eg.: 1.200 will be 1.2)
-
strip_insignificant_zeros: false
-
},
-
-
# Used in number_to_currency
-
currency: {
-
format: {
-
format: "%u%n",
-
negative_format: "-%u%n",
-
unit: "$",
-
# These five are to override number.format and are optional
-
separator: ".",
-
delimiter: ",",
-
precision: 2,
-
significant: false,
-
strip_insignificant_zeros: false
-
}
-
},
-
-
# Used in number_to_percentage
-
percentage: {
-
format: {
-
delimiter: "",
-
format: "%n%"
-
}
-
},
-
-
# Used in number_to_rounded
-
precision: {
-
format: {
-
delimiter: ""
-
}
-
},
-
-
# Used in number_to_human_size and number_to_human
-
human: {
-
format: {
-
# These five are to override number.format and are optional
-
delimiter: "",
-
precision: 3,
-
significant: true,
-
strip_insignificant_zeros: true
-
},
-
# Used in number_to_human_size
-
storage_units: {
-
# Storage units output formatting.
-
# %u is the storage unit, %n is the number (default: 2 MB)
-
format: "%n %u",
-
units: {
-
byte: "Bytes",
-
kb: "KB",
-
mb: "MB",
-
gb: "GB",
-
tb: "TB"
-
}
-
},
-
# Used in number_to_human
-
decimal_units: {
-
format: "%n %u",
-
# Decimal units output formatting
-
# By default we will only quantify some of the exponents
-
# but the commented ones might be defined or overridden
-
# by the user.
-
units: {
-
# femto: Quadrillionth
-
# pico: Trillionth
-
# nano: Billionth
-
# micro: Millionth
-
# mili: Thousandth
-
# centi: Hundredth
-
# deci: Tenth
-
unit: "",
-
# ten:
-
# one: Ten
-
# other: Tens
-
# hundred: Hundred
-
thousand: "Thousand",
-
million: "Million",
-
billion: "Billion",
-
trillion: "Trillion",
-
quadrillion: "Quadrillion"
-
}
-
}
-
}
-
}
-
-
1
DECIMAL_UNITS = { 0 => :unit, 1 => :ten, 2 => :hundred, 3 => :thousand, 6 => :million, 9 => :billion, 12 => :trillion, 15 => :quadrillion,
-
-1 => :deci, -2 => :centi, -3 => :mili, -6 => :micro, -9 => :nano, -12 => :pico, -15 => :femto }
-
-
1
STORAGE_UNITS = [:byte, :kb, :mb, :gb, :tb]
-
-
# Formats a +number+ into a US phone number (e.g., (555)
-
# 123-9876). You can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:area_code</tt> - Adds parentheses around the area code.
-
# * <tt>:delimiter</tt> - Specifies the delimiter to use
-
# (defaults to "-").
-
# * <tt>:extension</tt> - Specifies an extension to add to the
-
# end of the generated number.
-
# * <tt>:country_code</tt> - Sets the country code for the phone
-
# number.
-
# ==== Examples
-
#
-
# number_to_phone(5551234) # => 555-1234
-
# number_to_phone('5551234') # => 555-1234
-
# number_to_phone(1235551234) # => 123-555-1234
-
# number_to_phone(1235551234, area_code: true) # => (123) 555-1234
-
# number_to_phone(1235551234, delimiter: ' ') # => 123 555 1234
-
# number_to_phone(1235551234, area_code: true, extension: 555) # => (123) 555-1234 x 555
-
# number_to_phone(1235551234, country_code: 1) # => +1-123-555-1234
-
# number_to_phone('123a456') # => 123a456
-
#
-
# number_to_phone(1235551234, country_code: 1, extension: 1343, delimiter: '.')
-
# # => +1.123.555.1234 x 1343
-
1
def number_to_phone(number, options = {})
-
62
return unless number
-
59
options = options.symbolize_keys
-
-
59
number = number.to_s.strip
-
59
area_code = options[:area_code]
-
59
delimiter = options[:delimiter] || "-"
-
59
extension = options[:extension]
-
59
country_code = options[:country_code]
-
-
59
if area_code
-
11
number.gsub!(/(\d{1,3})(\d{3})(\d{4}$)/,"(\\1) \\2#{delimiter}\\3")
-
else
-
48
number.gsub!(/(\d{0,3})(\d{3})(\d{4})$/,"\\1#{delimiter}\\2#{delimiter}\\3")
-
48
number.slice!(0, 1) if number.start_with?(delimiter) && !delimiter.blank?
-
end
-
-
59
str = ''
-
59
str << "+#{country_code}#{delimiter}" unless country_code.blank?
-
59
str << number
-
59
str << " x #{extension}" unless extension.blank?
-
59
str
-
end
-
-
# Formats a +number+ into a currency string (e.g., $13.65). You
-
# can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the level of precision (defaults
-
# to 2).
-
# * <tt>:unit</tt> - Sets the denomination of the currency
-
# (defaults to "$").
-
# * <tt>:separator</tt> - Sets the separator between the units
-
# (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to ",").
-
# * <tt>:format</tt> - Sets the format for non-negative numbers
-
# (defaults to "%u%n"). Fields are <tt>%u</tt> for the
-
# currency, and <tt>%n</tt> for the number.
-
# * <tt>:negative_format</tt> - Sets the format for negative
-
# numbers (defaults to prepending an hyphen to the formatted
-
# number given by <tt>:format</tt>). Accepts the same fields
-
# than <tt>:format</tt>, except <tt>%n</tt> is here the
-
# absolute value of the number.
-
#
-
# ==== Examples
-
#
-
# number_to_currency(1234567890.50) # => $1,234,567,890.50
-
# number_to_currency(1234567890.506) # => $1,234,567,890.51
-
# number_to_currency(1234567890.506, precision: 3) # => $1,234,567,890.506
-
# number_to_currency(1234567890.506, locale: :fr) # => 1 234 567 890,51 €
-
# number_to_currency('123a456') # => $123a456
-
#
-
# number_to_currency(-1234567890.50, negative_format: '(%u%n)')
-
# # => ($1,234,567,890.50)
-
# number_to_currency(1234567890.50, unit: '£', separator: ',', delimiter: '')
-
# # => £1234567890,50
-
# number_to_currency(1234567890.50, unit: '£', separator: ',', delimiter: '', format: '%n %u')
-
# # => 1234567890,50 £
-
1
def number_to_currency(number, options = {})
-
66
return unless number
-
63
options = options.symbolize_keys
-
-
63
currency = i18n_format_options(options[:locale], :currency)
-
63
currency[:negative_format] ||= "-" + currency[:format] if currency[:format]
-
-
63
defaults = default_format_options(:currency).merge!(currency)
-
63
defaults[:negative_format] = "-" + options[:format] if options[:format]
-
63
options = defaults.merge!(options)
-
-
63
unit = options.delete(:unit)
-
63
format = options.delete(:format)
-
-
63
if number.to_f.phase != 0
-
22
format = options.delete(:negative_format)
-
22
number = number.respond_to?("abs") ? number.abs : number.sub(/^-/, '')
-
end
-
-
63
format.gsub('%n', self.number_to_rounded(number, options)).gsub('%u', unit)
-
end
-
-
# Formats a +number+ as a percentage string (e.g., 65%). You can
-
# customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +false+).
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +false+).
-
# * <tt>:format</tt> - Specifies the format of the percentage
-
# string The number field is <tt>%n</tt> (defaults to "%n%").
-
#
-
# ==== Examples
-
#
-
# number_to_percentage(100) # => 100.000%
-
# number_to_percentage('98') # => 98.000%
-
# number_to_percentage(100, precision: 0) # => 100%
-
# number_to_percentage(1000, delimiter: '.', separator: ,') # => 1.000,000%
-
# number_to_percentage(302.24398923423, precision: 5) # => 302.24399%
-
# number_to_percentage(1000, locale: :fr) # => 1 000,000%
-
# number_to_percentage('98a') # => 98a%
-
# number_to_percentage(100, format: '%n %') # => 100 %
-
1
def number_to_percentage(number, options = {})
-
45
return unless number
-
42
options = options.symbolize_keys
-
-
42
defaults = format_options(options[:locale], :percentage)
-
42
options = defaults.merge!(options)
-
-
42
format = options[:format] || "%n%"
-
42
format.gsub('%n', self.number_to_rounded(number, options))
-
end
-
-
# Formats a +number+ with grouped thousands using +delimiter+
-
# (e.g., 12,324). You can customize the format in the +options+
-
# hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to ",").
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
#
-
# ==== Examples
-
#
-
# number_to_delimited(12345678) # => 12,345,678
-
# number_to_delimited('123456') # => 123,456
-
# number_to_delimited(12345678.05) # => 12,345,678.05
-
# number_to_delimited(12345678, delimiter: '.') # => 12.345.678
-
# number_to_delimited(12345678, delimiter: ',') # => 12,345,678
-
# number_to_delimited(12345678.05, separator: ' ') # => 12,345,678 05
-
# number_to_delimited(12345678.05, locale: :fr) # => 12 345 678,05
-
# number_to_delimited('112a') # => 112a
-
# number_to_delimited(98765432.98, delimiter: ' ', separator: ',')
-
# # => 98 765 432,98
-
1
def number_to_delimited(number, options = {})
-
661
options = options.symbolize_keys
-
-
661
return number unless valid_float?(number)
-
-
655
options = format_options(options[:locale]).merge!(options)
-
-
655
parts = number.to_s.to_str.split('.')
-
655
parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{options[:delimiter]}")
-
655
parts.join(options[:separator])
-
end
-
-
# Formats a +number+ with the specified level of
-
# <tt>:precision</tt> (e.g., 112.32 has a precision of 2 if
-
# +:significant+ is +false+, and 5 if +:significant+ is +true+).
-
# You can customize the format in the +options+ hash.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +false+).
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +false+).
-
#
-
# ==== Examples
-
#
-
# number_to_rounded(111.2345) # => 111.235
-
# number_to_rounded(111.2345, precision: 2) # => 111.23
-
# number_to_rounded(13, precision: 5) # => 13.00000
-
# number_to_rounded(389.32314, precision: 0) # => 389
-
# number_to_rounded(111.2345, significant: true) # => 111
-
# number_to_rounded(111.2345, precision: 1, significant: true) # => 100
-
# number_to_rounded(13, precision: 5, significant: true) # => 13.000
-
# number_to_rounded(111.234, locale: :fr) # => 111,234
-
#
-
# number_to_rounded(13, precision: 5, significant: true, strip_insignificant_zeros: true)
-
# # => 13
-
#
-
# number_to_rounded(389.32314, precision: 4, significant: true) # => 389.3
-
# number_to_rounded(1111.2345, precision: 2, separator: ',', delimiter: '.')
-
# # => 1.111,23
-
1
def number_to_rounded(number, options = {})
-
610
return number unless valid_float?(number)
-
592
number = Float(number)
-
592
options = options.symbolize_keys
-
-
592
defaults = format_options(options[:locale], :precision)
-
592
options = defaults.merge!(options)
-
-
592
precision = options.delete :precision
-
592
significant = options.delete :significant
-
592
strip_insignificant_zeros = options.delete :strip_insignificant_zeros
-
-
592
if significant && precision > 0
-
382
if number == 0
-
16
digits, rounded_number = 1, 0
-
else
-
366
digits = (Math.log10(number.abs) + 1).floor
-
366
rounded_number = (BigDecimal.new(number.to_s) / BigDecimal.new((10 ** (digits - precision)).to_f.to_s)).round.to_f * 10 ** (digits - precision)
-
366
digits = (Math.log10(rounded_number.abs) + 1).floor # After rounding, the number of digits may have changed
-
end
-
382
precision -= digits
-
382
precision = 0 if precision < 0 # don't let it be negative
-
else
-
210
rounded_number = BigDecimal.new(number.to_s).round(precision).to_f
-
210
rounded_number = rounded_number.abs if rounded_number.zero? # prevent showing negative zeros
-
end
-
592
formatted_number = self.number_to_delimited("%01.#{precision}f" % rounded_number, options)
-
592
if strip_insignificant_zeros
-
328
escaped_separator = Regexp.escape(options[:separator])
-
328
formatted_number.sub(/(#{escaped_separator})(\d*[1-9])?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, '')
-
else
-
264
formatted_number
-
end
-
end
-
-
# Formats the bytes in +number+ into a more understandable
-
# representation (e.g., giving it 1500 yields 1.5 KB). This
-
# method is useful for reporting file sizes to users. You can
-
# customize the format in the +options+ hash.
-
#
-
# See <tt>number_to_human</tt> if you want to pretty-print a
-
# generic number.
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +true+)
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +true+)
-
# * <tt>:prefix</tt> - If +:si+ formats the number using the SI
-
# prefix (defaults to :binary)
-
#
-
# ==== Examples
-
#
-
# number_to_human_size(123) # => 123 Bytes
-
# number_to_human_size(1234) # => 1.21 KB
-
# number_to_human_size(12345) # => 12.1 KB
-
# number_to_human_size(1234567) # => 1.18 MB
-
# number_to_human_size(1234567890) # => 1.15 GB
-
# number_to_human_size(1234567890123) # => 1.12 TB
-
# number_to_human_size(1234567, precision: 2) # => 1.2 MB
-
# number_to_human_size(483989, precision: 2) # => 470 KB
-
# number_to_human_size(1234567, precision: 2, separator: ',') # => 1,2 MB
-
#
-
# Non-significant zeros after the fractional separator are stripped out by
-
# default (set <tt>:strip_insignificant_zeros</tt> to +false+ to change that):
-
#
-
# number_to_human_size(1234567890123, precision: 5) # => "1.1229 TB"
-
# number_to_human_size(524288000, precision: 5) # => "500 MB"
-
1
def number_to_human_size(number, options = {})
-
206
options = options.symbolize_keys
-
-
206
return number unless valid_float?(number)
-
200
number = Float(number)
-
-
200
defaults = format_options(options[:locale], :human)
-
200
options = defaults.merge!(options)
-
-
#for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files
-
200
options[:strip_insignificant_zeros] = true if not options.key?(:strip_insignificant_zeros)
-
-
200
storage_units_format = translate_number_value_with_default('human.storage_units.format', :locale => options[:locale], :raise => true)
-
-
200
base = options[:prefix] == :si ? 1000 : 1024
-
-
200
if number.to_i < base
-
61
unit = translate_number_value_with_default('human.storage_units.units.byte', :locale => options[:locale], :count => number.to_i, :raise => true)
-
61
storage_units_format.gsub(/%n/, number.to_i.to_s).gsub(/%u/, unit)
-
else
-
139
max_exp = STORAGE_UNITS.size - 1
-
139
exponent = (Math.log(number) / Math.log(base)).to_i # Convert to base
-
139
exponent = max_exp if exponent > max_exp # we need this to avoid overflow for the highest unit
-
139
number /= base ** exponent
-
-
139
unit_key = STORAGE_UNITS[exponent]
-
139
unit = translate_number_value_with_default("human.storage_units.units.#{unit_key}", :locale => options[:locale], :count => number, :raise => true)
-
-
139
formatted_number = self.number_to_rounded(number, options)
-
139
storage_units_format.gsub(/%n/, formatted_number).gsub(/%u/, unit)
-
end
-
end
-
-
# Pretty prints (formats and approximates) a number in a way it
-
# is more readable by humans (eg.: 1200000000 becomes "1.2
-
# Billion"). This is useful for numbers that can get very large
-
# (and too hard to read).
-
#
-
# See <tt>number_to_human_size</tt> if you want to print a file
-
# size.
-
#
-
# You can also define you own unit-quantifier names if you want
-
# to use other decimal units (eg.: 1500 becomes "1.5
-
# kilometers", 0.150 becomes "150 milliliters", etc). You may
-
# define a wide range of unit quantifiers, even fractional ones
-
# (centi, deci, mili, etc).
-
#
-
# ==== Options
-
#
-
# * <tt>:locale</tt> - Sets the locale to be used for formatting
-
# (defaults to current locale).
-
# * <tt>:precision</tt> - Sets the precision of the number
-
# (defaults to 3).
-
# * <tt>:significant</tt> - If +true+, precision will be the #
-
# of significant_digits. If +false+, the # of fractional
-
# digits (defaults to +true+)
-
# * <tt>:separator</tt> - Sets the separator between the
-
# fractional and integer digits (defaults to ".").
-
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults
-
# to "").
-
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes
-
# insignificant zeros after the decimal separator (defaults to
-
# +true+)
-
# * <tt>:units</tt> - A Hash of unit quantifier names. Or a
-
# string containing an i18n scope where to find this hash. It
-
# might have the following keys:
-
# * *integers*: <tt>:unit</tt>, <tt>:ten</tt>,
-
# *<tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>,
-
# *<tt>:billion</tt>, <tt>:trillion</tt>,
-
# *<tt>:quadrillion</tt>
-
# * *fractionals*: <tt>:deci</tt>, <tt>:centi</tt>,
-
# *<tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>,
-
# *<tt>:pico</tt>, <tt>:femto</tt>
-
# * <tt>:format</tt> - Sets the format of the output string
-
# (defaults to "%n %u"). The field types are:
-
# * %u - The quantifier (ex.: 'thousand')
-
# * %n - The number
-
#
-
# ==== Examples
-
#
-
# number_to_human(123) # => "123"
-
# number_to_human(1234) # => "1.23 Thousand"
-
# number_to_human(12345) # => "12.3 Thousand"
-
# number_to_human(1234567) # => "1.23 Million"
-
# number_to_human(1234567890) # => "1.23 Billion"
-
# number_to_human(1234567890123) # => "1.23 Trillion"
-
# number_to_human(1234567890123456) # => "1.23 Quadrillion"
-
# number_to_human(1234567890123456789) # => "1230 Quadrillion"
-
# number_to_human(489939, precision: 2) # => "490 Thousand"
-
# number_to_human(489939, precision: 4) # => "489.9 Thousand"
-
# number_to_human(1234567, precision: 4,
-
# significant: false) # => "1.2346 Million"
-
# number_to_human(1234567, precision: 1,
-
# separator: ',',
-
# significant: false) # => "1,2 Million"
-
#
-
# Non-significant zeros after the decimal separator are stripped
-
# out by default (set <tt>:strip_insignificant_zeros</tt> to
-
# +false+ to change that):
-
#
-
# number_to_human(12345012345, significant_digits: 6) # => "12.345 Billion"
-
# number_to_human(500000000, precision: 5) # => "500 Million"
-
#
-
# ==== Custom Unit Quantifiers
-
#
-
# You can also use your own custom unit quantifiers:
-
# number_to_human(500000, units: { unit: 'ml', thousand: 'lt' }) # => "500 lt"
-
#
-
# If in your I18n locale you have:
-
#
-
# distance:
-
# centi:
-
# one: "centimeter"
-
# other: "centimeters"
-
# unit:
-
# one: "meter"
-
# other: "meters"
-
# thousand:
-
# one: "kilometer"
-
# other: "kilometers"
-
# billion: "gazillion-distance"
-
#
-
# Then you could do:
-
#
-
# number_to_human(543934, units: :distance) # => "544 kilometers"
-
# number_to_human(54393498, units: :distance) # => "54400 kilometers"
-
# number_to_human(54393498000, units: :distance) # => "54.4 gazillion-distance"
-
# number_to_human(343, units: :distance, precision: 1) # => "300 meters"
-
# number_to_human(1, units: :distance) # => "1 meter"
-
# number_to_human(0.34, units: :distance) # => "34 centimeters"
-
1
def number_to_human(number, options = {})
-
184
options = options.symbolize_keys
-
-
184
return number unless valid_float?(number)
-
178
number = Float(number)
-
-
178
defaults = format_options(options[:locale], :human)
-
178
options = defaults.merge!(options)
-
-
#for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files
-
178
options[:strip_insignificant_zeros] = true if not options.key?(:strip_insignificant_zeros)
-
-
178
inverted_du = DECIMAL_UNITS.invert
-
-
178
units = options.delete :units
-
178
unit_exponents = case units
-
when Hash
-
80
units
-
when String, Symbol
-
1
I18n.translate(:"#{units}", :locale => options[:locale], :raise => true)
-
when nil
-
97
translate_number_value_with_default("human.decimal_units.units", :locale => options[:locale], :raise => true)
-
else
-
raise ArgumentError, ":units must be a Hash or String translation scope."
-
1962
end.keys.map{|e_name| inverted_du[e_name] }.sort_by{|e| -e}
-
-
178
number_exponent = number != 0 ? Math.log10(number.abs).floor : 0
-
819
display_exponent = unit_exponents.find{ |e| number_exponent >= e } || 0
-
178
number /= 10 ** display_exponent
-
-
178
unit = case units
-
when Hash
-
80
units[DECIMAL_UNITS[display_exponent]]
-
when String, Symbol
-
1
I18n.translate(:"#{units}.#{DECIMAL_UNITS[display_exponent]}", :locale => options[:locale], :count => number.to_i)
-
else
-
97
translate_number_value_with_default("human.decimal_units.units.#{DECIMAL_UNITS[display_exponent]}", :locale => options[:locale], :count => number.to_i)
-
end
-
-
178
decimal_format = options[:format] || translate_number_value_with_default('human.decimal_units.format', :locale => options[:locale])
-
178
formatted_number = self.number_to_rounded(number, options)
-
178
decimal_format.gsub(/%n/, formatted_number).gsub(/%u/, unit).strip
-
end
-
-
1
def self.private_module_and_instance_method(method_name) #:nodoc:
-
5
private method_name
-
5
private_class_method method_name
-
end
-
1
private_class_method :private_module_and_instance_method
-
-
1
def format_options(locale, namespace = nil) #:nodoc:
-
1667
default_format_options(namespace).merge!(i18n_format_options(locale, namespace))
-
end
-
1
private_module_and_instance_method :format_options
-
-
1
def default_format_options(namespace = nil) #:nodoc:
-
1730
options = DEFAULTS[:format].dup
-
1730
options.merge!(DEFAULTS[namespace][:format]) if namespace
-
1730
options
-
end
-
1
private_module_and_instance_method :default_format_options
-
-
1
def i18n_format_options(locale, namespace = nil) #:nodoc:
-
1730
options = I18n.translate(:'number.format', locale: locale, default: {}).dup
-
1730
if namespace
-
1075
options.merge!(I18n.translate(:"number.#{namespace}.format", locale: locale, default: {}))
-
end
-
1730
options
-
end
-
1
private_module_and_instance_method :i18n_format_options
-
-
1
def translate_number_value_with_default(key, i18n_options = {}) #:nodoc:
-
3353
default = key.split('.').reduce(DEFAULTS) { |defaults, k| defaults[k.to_sym] }
-
-
764
I18n.translate(key, { default: default, scope: :number }.merge!(i18n_options))
-
end
-
1
private_module_and_instance_method :translate_number_value_with_default
-
-
1
def valid_float?(number) #:nodoc:
-
1661
Float(number)
-
rescue ArgumentError, TypeError
-
36
false
-
end
-
1
private_module_and_instance_method :valid_float?
-
end
-
end
-
1
require 'active_support/core_ext/hash/deep_merge'
-
-
1
module ActiveSupport
-
1
class OptionMerger #:nodoc:
-
1
instance_methods.each do |method|
-
139
undef_method(method) if method !~ /^(__|instance_eval|class|object_id)/
-
end
-
-
1
def initialize(context, options)
-
12
@context, @options = context, options
-
end
-
-
1
private
-
1
def method_missing(method, *arguments, &block)
-
12
if arguments.last.is_a?(Proc)
-
1
proc = arguments.pop
-
2
arguments << lambda { |*args| @options.deep_merge(proc.call(*args)) }
-
else
-
11
arguments << (arguments.last.respond_to?(:to_hash) ? @options.deep_merge(arguments.pop) : @options.dup)
-
end
-
-
12
@context.__send__(method, *arguments, &block)
-
end
-
end
-
end
-
1
require 'yaml'
-
-
1
YAML.add_builtin_type("omap") do |type, val|
-
ActiveSupport::OrderedHash[val.map{ |v| v.to_a.first }]
-
end
-
-
1
module ActiveSupport
-
# <tt>ActiveSupport::OrderedHash</tt> implements a hash that preserves
-
# insertion order.
-
#
-
# oh = ActiveSupport::OrderedHash.new
-
# oh[:a] = 1
-
# oh[:b] = 2
-
# oh.keys # => [:a, :b], this order is guaranteed
-
#
-
# Also, maps the +omap+ feature for YAML files
-
# (See http://yaml.org/type/omap.html) to support ordered items
-
# when loading from yaml.
-
#
-
# <tt>ActiveSupport::OrderedHash</tt> is namespaced to prevent conflicts
-
# with other implementations.
-
1
class OrderedHash < ::Hash
-
1
def to_yaml_type
-
"!tag:yaml.org,2002:omap"
-
end
-
-
1
def encode_with(coder)
-
38
coder.represent_seq '!omap', map { |k,v| { k => v } }
-
end
-
-
1
def nested_under_indifferent_access
-
1
self
-
end
-
-
# Returns true to make sure that this hash is extractable via <tt>Array#extract_options!</tt>
-
1
def extractable_options?
-
1
true
-
end
-
end
-
end
-
1
module ActiveSupport
-
# Usually key value pairs are handled something like this:
-
#
-
# h = {}
-
# h[:boy] = 'John'
-
# h[:girl] = 'Mary'
-
# h[:boy] # => 'John'
-
# h[:girl] # => 'Mary'
-
#
-
# Using +OrderedOptions+, the above code could be reduced to:
-
#
-
# h = ActiveSupport::OrderedOptions.new
-
# h.boy = 'John'
-
# h.girl = 'Mary'
-
# h.boy # => 'John'
-
# h.girl # => 'Mary'
-
1
class OrderedOptions < Hash
-
1
alias_method :_get, :[] # preserve the original #[] method
-
1
protected :_get # make it protected
-
-
1
def []=(key, value)
-
26
super(key.to_sym, value)
-
end
-
-
1
def [](key)
-
21
super(key.to_sym)
-
end
-
-
1
def method_missing(name, *args)
-
35
name_string = name.to_s
-
35
if name_string.chomp!('=')
-
18
self[name_string] = args.first
-
else
-
17
self[name]
-
end
-
end
-
-
1
def respond_to_missing?(name, include_private)
-
4
true
-
end
-
end
-
-
1
class InheritableOptions < OrderedOptions
-
1
def initialize(parent = nil)
-
14
if parent.kind_of?(OrderedOptions)
-
# use the faster _get when dealing with OrderedOptions
-
14
super() { |h,k| parent._get(k) }
-
5
elsif parent
-
super() { |h,k| parent[k] }
-
else
-
5
super()
-
end
-
end
-
-
1
def inheritable_copy
-
7
self.class.new(self)
-
end
-
end
-
end
-
# This is private interface.
-
#
-
# Rails components cherry pick from Active Support as needed, but there are a
-
# few features that are used for sure some way or another and it is not worth
-
# to put individual requires absolutely everywhere. Think blank? for example.
-
#
-
# This file is loaded by every Rails component except Active Support itself,
-
# but it does not belong to the Rails public interface. It is internal to
-
# Rails and can change anytime.
-
-
# Defines Object#blank? and Object#present?.
-
1
require 'active_support/core_ext/object/blank'
-
-
# Rails own autoload, eager_load, etc.
-
1
require 'active_support/dependencies/autoload'
-
-
# Support for ClassMethods and the included macro.
-
1
require 'active_support/concern'
-
-
# Defines Class#class_attribute.
-
1
require 'active_support/core_ext/class/attribute'
-
-
# Defines Module#delegate.
-
1
require 'active_support/core_ext/module/delegation'
-
-
# Defines ActiveSupport::Deprecation.
-
1
require 'active_support/deprecation'
-
1
require 'active_support/concern'
-
1
require 'active_support/core_ext/class/attribute'
-
1
require 'active_support/core_ext/proc'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/core_ext/array/extract_options'
-
-
1
module ActiveSupport
-
# Rescuable module adds support for easier exception handling.
-
1
module Rescuable
-
1
extend Concern
-
-
1
included do
-
1
class_attribute :rescue_handlers
-
1
self.rescue_handlers = []
-
end
-
-
1
module ClassMethods
-
# Rescue exceptions raised in controller actions.
-
#
-
# <tt>rescue_from</tt> receives a series of exception classes or class
-
# names, and a trailing <tt>:with</tt> option with the name of a method
-
# or a Proc object to be called to handle them. Alternatively a block can
-
# be given.
-
#
-
# Handlers that take one argument will be called with the exception, so
-
# that the exception can be inspected when dealing with it.
-
#
-
# Handlers are inherited. They are searched from right to left, from
-
# bottom to top, and up the hierarchy. The handler of the first class for
-
# which <tt>exception.is_a?(klass)</tt> holds true is the one invoked, if
-
# any.
-
#
-
# class ApplicationController < ActionController::Base
-
# rescue_from User::NotAuthorized, with: :deny_access # self defined exception
-
# rescue_from ActiveRecord::RecordInvalid, with: :show_errors
-
#
-
# rescue_from 'MyAppError::Base' do |exception|
-
# render xml: exception, status: 500
-
# end
-
#
-
# protected
-
# def deny_access
-
# ...
-
# end
-
#
-
# def show_errors(exception)
-
# exception.record.new_record? ? ...
-
# end
-
# end
-
#
-
# Exceptions raised inside exception handlers are not propagated up.
-
1
def rescue_from(*klasses, &block)
-
5
options = klasses.extract_options!
-
-
5
unless options.has_key?(:with)
-
2
if block_given?
-
2
options[:with] = block
-
else
-
raise ArgumentError, "Need a handler. Supply an options hash that has a :with key as the last argument."
-
end
-
end
-
-
5
klasses.each do |klass|
-
5
key = if klass.is_a?(Class) && klass <= Exception
-
5
klass.name
-
elsif klass.is_a?(String)
-
klass
-
else
-
raise ArgumentError, "#{klass} is neither an Exception nor a String"
-
end
-
-
# put the new handler at the end because the list is read in reverse
-
5
self.rescue_handlers += [[key, options[:with]]]
-
end
-
end
-
end
-
-
# Tries to rescue the exception by looking up and calling a registered handler.
-
1
def rescue_with_handler(exception)
-
3
if handler = handler_for_rescue(exception)
-
3
handler.arity != 0 ? handler.call(exception) : handler.call
-
3
true # don't rely on the return value of the handler
-
end
-
end
-
-
1
def handler_for_rescue(exception)
-
# We go from right to left because pairs are pushed onto rescue_handlers
-
# as rescue_from declarations are found.
-
3
_, rescuer = self.class.rescue_handlers.reverse.detect do |klass_name, handler|
-
# The purpose of allowing strings in rescue_from is to support the
-
# declaration of handler associations for exception classes whose
-
# definition is yet unknown.
-
#
-
# Since this loop needs the constants it would be inconsistent to
-
# assume they should exist at this point. An early raised exception
-
# could trigger some other handler and the array could include
-
# precisely a string whose corresponding constant has not yet been
-
# seen. This is why we are tolerant to unknown constants.
-
#
-
# Note that this tolerance only matters if the exception was given as
-
# a string, otherwise a NameError will be raised by the interpreter
-
# itself when rescue_from CONSTANT is executed.
-
6
klass = self.class.const_get(klass_name) rescue nil
-
6
klass ||= klass_name.constantize rescue nil
-
6
exception.is_a?(klass) if klass
-
end
-
-
3
case rescuer
-
when Symbol
-
1
method(rescuer)
-
when Proc
-
2
if rescuer.arity == 0
-
2
Proc.new { instance_exec(&rescuer) }
-
else
-
2
Proc.new { |_exception| instance_exec(_exception, &rescuer) }
-
end
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
# Wrapping a string in this class gives you a prettier way to test
-
# for equality. The value returned by <tt>Rails.env</tt> is wrapped
-
# in a StringInquirer object so instead of calling this:
-
#
-
# Rails.env == 'production'
-
#
-
# you can call this:
-
#
-
# Rails.env.production?
-
1
class StringInquirer < String
-
1
private
-
-
1
def respond_to_missing?(method_name, include_private = false)
-
1
method_name[-1] == '?'
-
end
-
-
1
def method_missing(method_name, *arguments)
-
5
if method_name[-1] == '?'
-
4
self == method_name[0..-2]
-
else
-
1
super
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'logger'
-
1
require 'active_support/logger'
-
-
1
module ActiveSupport
-
# Wraps any standard Logger object to provide tagging capabilities.
-
#
-
# logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
-
# logger.tagged('BCX') { logger.info 'Stuff' } # Logs "[BCX] Stuff"
-
# logger.tagged('BCX', "Jason") { logger.info 'Stuff' } # Logs "[BCX] [Jason] Stuff"
-
# logger.tagged('BCX') { logger.tagged('Jason') { logger.info 'Stuff' } } # Logs "[BCX] [Jason] Stuff"
-
#
-
# This is used by the default Rails.logger as configured by Railties to make
-
# it easy to stamp log lines with subdomains, request ids, and anything else
-
# to aid debugging of multi-user production applications.
-
1
module TaggedLogging
-
1
module Formatter # :nodoc:
-
# This method is invoked when a log event occurs.
-
1
def call(severity, timestamp, progname, msg)
-
18
super(severity, timestamp, progname, "#{tags_text}#{msg}")
-
end
-
-
1
def tagged(*tags)
-
13
new_tags = push_tags(*tags)
-
13
yield self
-
ensure
-
13
pop_tags(new_tags.size)
-
end
-
-
1
def push_tags(*tags)
-
15
tags.flatten.reject(&:blank?).tap do |new_tags|
-
15
current_tags.concat new_tags
-
end
-
end
-
-
1
def pop_tags(size = 1)
-
16
current_tags.pop size
-
end
-
-
1
def clear_tags!
-
2
current_tags.clear
-
end
-
-
1
def current_tags
-
51
Thread.current[:activesupport_tagged_logging_tags] ||= []
-
end
-
-
1
private
-
1
def tags_text
-
18
tags = current_tags
-
18
if tags.any?
-
38
tags.collect { |tag| "[#{tag}] " }.join
-
end
-
end
-
end
-
-
1
def self.new(logger)
-
# Ensure we set a default formatter so we aren't extending nil!
-
14
logger.formatter ||= ActiveSupport::Logger::SimpleFormatter.new
-
14
logger.formatter.extend Formatter
-
14
logger.extend(self)
-
end
-
-
1
delegate :push_tags, :pop_tags, :clear_tags!, to: :formatter
-
-
1
def tagged(*tags)
-
26
formatter.tagged(*tags) { yield self }
-
end
-
-
1
def flush
-
1
clear_tags!
-
1
super if defined?(super)
-
end
-
end
-
end
-
1
gem 'minitest' # make sure we get the gem, not stdlib
-
1
require 'minitest/spec'
-
1
require 'active_support/testing/tagged_logging'
-
1
require 'active_support/testing/setup_and_teardown'
-
1
require 'active_support/testing/assertions'
-
1
require 'active_support/testing/deprecation'
-
1
require 'active_support/testing/isolation'
-
1
require 'active_support/testing/mocha_module'
-
1
require 'active_support/testing/constant_lookup'
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/deprecation'
-
-
1
module ActiveSupport
-
1
class TestCase < ::MiniTest::Spec
-
-
1
include ActiveSupport::Testing::MochaModule
-
-
# Use AS::TestCase for the base class when describing a model
-
1
register_spec_type(self) do |desc|
-
2
Class === desc && desc < ActiveRecord::Base
-
end
-
-
1
Assertion = MiniTest::Assertion
-
1
alias_method :method_name, :__name__
-
-
1
$tags = {}
-
1
def self.for_tag(tag)
-
yield if $tags[tag]
-
end
-
-
# FIXME: we have tests that depend on run order, we should fix that and
-
# remove this method.
-
1
def self.test_order # :nodoc:
-
330
:sorted
-
end
-
-
1
include ActiveSupport::Testing::TaggedLogging
-
1
include ActiveSupport::Testing::SetupAndTeardown
-
1
include ActiveSupport::Testing::Assertions
-
1
include ActiveSupport::Testing::Deprecation
-
-
1
def self.describe(text)
-
if block_given?
-
super
-
else
-
message = "`describe` without a block is deprecated, please switch to: `def self.name; #{text.inspect}; end`\n"
-
ActiveSupport::Deprecation.warn message
-
-
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
-
def self.name
-
"#{text}"
-
end
-
RUBY_EVAL
-
end
-
end
-
-
1
class << self
-
1
alias :test :it
-
end
-
-
# test/unit backwards compatibility methods
-
1
alias :assert_raise :assert_raises
-
1
alias :assert_not_nil :refute_nil
-
1
alias :assert_not_equal :refute_equal
-
1
alias :assert_no_match :refute_match
-
1
alias :assert_not_same :refute_same
-
-
# Fails if the block raises an exception.
-
#
-
# assert_nothing_raised do
-
# ...
-
# end
-
1
def assert_nothing_raised(*args)
-
44
yield
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/blank'
-
-
1
module ActiveSupport
-
1
module Testing
-
1
module Assertions
-
# Test numeric difference between the return value of an expression as a
-
# result of what is evaluated in the yielded block.
-
#
-
# assert_difference 'Article.count' do
-
# post :create, article: {...}
-
# end
-
#
-
# An arbitrary expression is passed in and evaluated.
-
#
-
# assert_difference 'assigns(:article).comments(:reload).size' do
-
# post :create, comment: {...}
-
# end
-
#
-
# An arbitrary positive or negative difference can be specified.
-
# The default is <tt>1</tt>.
-
#
-
# assert_difference 'Article.count', -1 do
-
# post :delete, id: ...
-
# end
-
#
-
# An array of expressions can also be passed in and evaluated.
-
#
-
# assert_difference [ 'Article.count', 'Post.count' ], 2 do
-
# post :create, article: {...}
-
# end
-
#
-
# A lambda or a list of lambdas can be passed in and evaluated:
-
#
-
# assert_difference ->{ Article.count }, 2 do
-
# post :create, article: {...}
-
# end
-
#
-
# assert_difference [->{ Article.count }, ->{ Post.count }], 2 do
-
# post :create, article: {...}
-
# end
-
#
-
# An error message can be specified.
-
#
-
# assert_difference 'Article.count', -1, 'An Article should be destroyed' do
-
# post :delete, id: ...
-
# end
-
1
def assert_difference(expression, difference = 1, message = nil, &block)
-
13
expressions = Array(expression)
-
-
13
exps = expressions.map { |e|
-
48
e.respond_to?(:call) ? e : lambda { eval(e, block.binding) }
-
}
-
29
before = exps.map { |e| e.call }
-
-
13
yield
-
-
13
expressions.zip(exps).each_with_index do |(code, e), i|
-
16
error = "#{code.inspect} didn't change by #{difference}"
-
16
error = "#{message}.\n#{error}" if message
-
16
assert_equal(before[i] + difference, e.call, error)
-
end
-
end
-
-
# Assertion that the numeric result of evaluating an expression is not
-
# changed before and after invoking the passed in block.
-
#
-
# assert_no_difference 'Article.count' do
-
# post :create, article: invalid_attributes
-
# end
-
#
-
# An error message can be specified.
-
#
-
# assert_no_difference 'Article.count', 'An Article should not be created' do
-
# post :create, article: invalid_attributes
-
# end
-
1
def assert_no_difference(expression, message = nil, &block)
-
1
assert_difference expression, 0, message, &block
-
end
-
-
# Test if an expression is blank. Passes if <tt>object.blank?</tt>
-
# is +true+.
-
#
-
# assert_blank [] # => true
-
# assert_blank [[]] # => [[]] is not blank
-
#
-
# An error message can be specified.
-
#
-
# assert_blank [], 'this should be blank'
-
1
def assert_blank(object, message=nil)
-
18
message ||= "#{object.inspect} is not blank"
-
18
assert object.blank?, message
-
end
-
-
# Test if an expression is not blank. Passes if <tt>object.present?</tt>
-
# is +true+.
-
#
-
# assert_present({ data: 'x' }) # => true
-
# assert_present({}) # => {} is blank
-
#
-
# An error message can be specified.
-
#
-
# assert_present({ data: 'x' }, 'this should not be blank')
-
1
def assert_present(object, message=nil)
-
18
message ||= "#{object.inspect} is blank"
-
18
assert object.present?, message
-
end
-
end
-
end
-
end
-
1
require "active_support/concern"
-
1
require "active_support/inflector"
-
-
1
module ActiveSupport
-
1
module Testing
-
# Resolves a constant from a minitest spec name.
-
#
-
# Given the following spec-style test:
-
#
-
# describe WidgetsController, :index do
-
# describe "authenticated user" do
-
# describe "returns widgets" do
-
# it "has a controller that exists" do
-
# assert_kind_of WidgetsController, @controller
-
# end
-
# end
-
# end
-
# end
-
#
-
# The test will have the following name:
-
#
-
# "WidgetsController::index::authenticated user::returns widgets"
-
#
-
# The constant WidgetsController can be resolved from the name.
-
# The following code will resolve the constant:
-
#
-
# controller = determine_constant_from_test_name(name) do |constant|
-
# Class === constant && constant < ::ActionController::Metal
-
# end
-
1
module ConstantLookup
-
1
extend ::ActiveSupport::Concern
-
-
1
module ClassMethods
-
1
def determine_constant_from_test_name(test_name)
-
22
names = test_name.split "::"
-
22
while names.size > 0 do
-
46
names.last.sub!(/Test$/, "")
-
46
begin
-
46
constant = names.join("::").constantize
-
12
break(constant) if yield(constant)
-
rescue NameError
-
# Constant wasn't found, move on
-
ensure
-
46
names.pop
-
end
-
end
-
end
-
end
-
-
end
-
end
-
end
-
1
require 'active_support/deprecation'
-
-
1
module ActiveSupport
-
1
module Testing
-
1
module Deprecation #:nodoc:
-
1
def assert_deprecated(match = nil, &block)
-
21
result, warnings = collect_deprecations(&block)
-
21
assert !warnings.empty?, "Expected a deprecation warning within the block but received none"
-
21
if match
-
13
match = Regexp.new(Regexp.escape(match)) unless match.is_a?(Regexp)
-
26
assert warnings.any? { |w| w =~ match }, "No deprecation warning matched #{match}: #{warnings.join(', ')}"
-
end
-
21
result
-
end
-
-
1
def assert_not_deprecated(&block)
-
7
result, deprecations = collect_deprecations(&block)
-
7
assert deprecations.empty?, "Expected no deprecation warning within the block but received #{deprecations.size}: \n #{deprecations * "\n "}"
-
7
result
-
end
-
-
1
private
-
1
def collect_deprecations
-
28
old_behavior = ActiveSupport::Deprecation.behavior
-
28
deprecations = []
-
28
ActiveSupport::Deprecation.behavior = Proc.new do |message, callstack|
-
23
deprecations << message
-
end
-
28
result = yield
-
28
[result, deprecations]
-
ensure
-
28
ActiveSupport::Deprecation.behavior = old_behavior
-
end
-
end
-
end
-
end
-
1
require 'rbconfig'
-
1
module ActiveSupport
-
1
module Testing
-
1
class RemoteError < StandardError
-
-
1
attr_reader :message, :backtrace
-
-
1
def initialize(exception)
-
@message = "caught #{exception.class.name}: #{exception.message}"
-
@backtrace = exception.backtrace
-
end
-
end
-
-
1
class ProxyTestResult
-
1
def initialize
-
@calls = []
-
end
-
-
1
def add_error(e)
-
e = Test::Unit::Error.new(e.test_name, RemoteError.new(e.exception))
-
@calls << [:add_error, e]
-
end
-
-
1
def __replay__(result)
-
6
@calls.each do |name, args|
-
6
result.send(name, *args)
-
end
-
end
-
-
1
def method_missing(name, *args)
-
@calls << [name, args]
-
end
-
end
-
-
1
module Isolation
-
1
require 'thread'
-
-
1
class ParallelEach
-
1
include Enumerable
-
-
# default to 2 cores
-
1
CORES = (ENV['TEST_CORES'] || 2).to_i
-
-
1
def initialize list
-
2
@list = list
-
2
@queue = SizedQueue.new CORES
-
end
-
-
1
def grep pattern
-
1
self.class.new super
-
end
-
-
1
def each
-
2
threads = CORES.times.map {
-
4
Thread.new {
-
4
while job = @queue.pop
-
12
yield job
-
end
-
}
-
}
-
14
@list.each { |i| @queue << i }
-
6
CORES.times { @queue << nil }
-
2
threads.each(&:join)
-
end
-
end
-
-
1
def self.included(klass) #:nodoc:
-
1
klass.extend(Module.new {
-
1
def test_methods
-
1
ParallelEach.new super
-
end
-
})
-
end
-
-
1
def self.forking_env?
-
1
!ENV["NO_FORK"] && ((RbConfig::CONFIG['host_os'] !~ /mswin|mingw/) && (RUBY_PLATFORM !~ /java/))
-
end
-
-
1
def _run_class_setup # class setup method should only happen in parent
-
6
unless defined?(@@ran_class_setup) || ENV['ISOLATION_TEST']
-
1
self.class.setup if self.class.respond_to?(:setup)
-
1
@@ran_class_setup = true
-
end
-
end
-
-
1
def run(runner)
-
6
_run_class_setup
-
-
6
serialized = run_in_isolation do |isolated_runner|
-
super(isolated_runner)
-
end
-
-
6
retval, proxy = Marshal.load(serialized)
-
6
proxy.__replay__(runner)
-
6
retval
-
end
-
-
1
module Forking
-
1
def run_in_isolation(&blk)
-
6
read, write = IO.pipe
-
-
6
pid = fork do
-
read.close
-
proxy = ProxyTestResult.new
-
retval = yield proxy
-
write.puts [Marshal.dump([retval, proxy])].pack("m")
-
exit!
-
end
-
-
6
write.close
-
6
result = read.read
-
6
Process.wait2(pid)
-
6
return result.unpack("m")[0]
-
end
-
end
-
-
1
module Subprocess
-
1
ORIG_ARGV = ARGV.dup unless defined?(ORIG_ARGV)
-
-
# Crazy H4X to get this working in windows / jruby with
-
# no forking.
-
1
def run_in_isolation(&blk)
-
require "tempfile"
-
-
if ENV["ISOLATION_TEST"]
-
proxy = ProxyTestResult.new
-
retval = yield proxy
-
File.open(ENV["ISOLATION_OUTPUT"], "w") do |file|
-
file.puts [Marshal.dump([retval, proxy])].pack("m")
-
end
-
exit!
-
else
-
Tempfile.open("isolation") do |tmpfile|
-
ENV["ISOLATION_TEST"] = @method_name
-
ENV["ISOLATION_OUTPUT"] = tmpfile.path
-
-
load_paths = $-I.map {|p| "-I\"#{File.expand_path(p)}\"" }.join(" ")
-
`#{Gem.ruby} #{load_paths} #{$0} #{ORIG_ARGV.join(" ")} -t\"#{self.class}\"`
-
-
ENV.delete("ISOLATION_TEST")
-
ENV.delete("ISOLATION_OUTPUT")
-
-
return tmpfile.read.unpack("m")[0]
-
end
-
end
-
end
-
end
-
-
1
include forking_env? ? Forking : Subprocess
-
end
-
end
-
end
-
1
module ActiveSupport
-
1
module Testing
-
1
module MochaModule
-
1
begin
-
1
require 'mocha/api'
-
1
include Mocha::API
-
-
1
def before_setup
-
2858
mocha_setup
-
2858
super
-
end
-
-
1
def after_teardown
-
2856
super
-
2856
mocha_verify
-
2856
mocha_teardown
-
end
-
rescue LoadError
-
end
-
end
-
end
-
end
-
1
require 'fileutils'
-
1
require 'active_support/concern'
-
1
require 'active_support/core_ext/class/delegating_attributes'
-
1
require 'active_support/core_ext/string/inflections'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'active_support/number_helper'
-
-
1
module ActiveSupport
-
1
module Testing
-
1
module Performance
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
superclass_delegating_accessor :profile_options
-
self.profile_options = {}
-
end
-
-
# each implementation should define metrics and freeze the defaults
-
1
DEFAULTS =
-
if ARGV.include?('--benchmark') # HAX for rake test
-
{ :runs => 4,
-
:output => 'tmp/performance',
-
:benchmark => true }
-
else
-
{ :runs => 1,
-
:output => 'tmp/performance',
-
1
:benchmark => false }
-
end
-
-
1
def full_profile_options
-
DEFAULTS.merge(profile_options)
-
end
-
-
1
def full_test_name
-
"#{self.class.name}##{method_name}"
-
end
-
-
1
def run(runner)
-
@runner = runner
-
-
run_warmup
-
if full_profile_options && metrics = full_profile_options[:metrics]
-
metrics.each do |metric_name|
-
if klass = Metrics[metric_name.to_sym]
-
run_profile(klass.new)
-
end
-
end
-
end
-
-
return
-
end
-
-
1
def run_test(metric, mode)
-
result = '.'
-
begin
-
run_callbacks :setup
-
setup
-
metric.send(mode) { __send__ method_name }
-
rescue Exception => e
-
result = @runner.puke(self.class, method_name, e)
-
ensure
-
begin
-
teardown
-
run_callbacks :teardown
-
rescue Exception => e
-
result = @runner.puke(self.class, method_name, e)
-
end
-
end
-
result
-
end
-
-
1
protected
-
# overridden by each implementation.
-
1
def run_gc; end
-
-
1
def run_warmup
-
run_gc
-
-
time = Metrics::Time.new
-
run_test(time, :benchmark)
-
puts "%s (%s warmup)" % [full_test_name, time.format(time.total)]
-
-
run_gc
-
end
-
-
1
def run_profile(metric)
-
klass = full_profile_options[:benchmark] ? Benchmarker : Profiler
-
performer = klass.new(self, metric)
-
-
performer.run
-
puts performer.report
-
performer.record
-
end
-
-
1
class Performer
-
1
delegate :run_test, :full_profile_options, :full_test_name, :to => :@harness
-
-
1
def initialize(harness, metric)
-
2
@harness, @metric, @supported = harness, metric, false
-
end
-
-
1
def report
-
if @supported
-
rate = @total / full_profile_options[:runs]
-
'%20s: %s' % [@metric.name, @metric.format(rate)]
-
else
-
'%20s: unsupported' % @metric.name
-
end
-
end
-
-
1
protected
-
1
def output_filename
-
"#{full_profile_options[:output]}/#{full_test_name}_#{@metric.name}"
-
end
-
end
-
-
# overridden by each implementation.
-
1
class Profiler < Performer
-
1
def time_with_block
-
before = Time.now
-
yield
-
Time.now - before
-
end
-
-
1
def run; end
-
1
def record; end
-
end
-
-
1
class Benchmarker < Performer
-
1
def initialize(*args)
-
2
super
-
2
@supported = @metric.respond_to?('measure')
-
end
-
-
1
def run
-
return unless @supported
-
-
full_profile_options[:runs].to_i.times { run_test(@metric, :benchmark) }
-
@total = @metric.total
-
end
-
-
1
def record
-
avg = @metric.total / full_profile_options[:runs].to_i
-
now = Time.now.utc.xmlschema
-
with_output_file do |file|
-
file.puts "#{avg},#{now},#{environment}"
-
end
-
end
-
-
1
def environment
-
@env ||= [].tap do |env|
-
2
env << "#{$1}.#{$2}" if File.directory?('.git') && `git branch -v` =~ /^\* (\S+)\s+(\S+)/
-
2
env << rails_version if defined?(Rails::VERSION::STRING)
-
2
env << "#{RUBY_ENGINE}-#{RUBY_VERSION}.#{RUBY_PATCHLEVEL}"
-
2
env << RUBY_PLATFORM
-
2
end.join(',')
-
end
-
-
1
protected
-
1
if defined?(Rails::VERSION::STRING)
-
HEADER = 'measurement,created_at,app,rails,ruby,platform'
-
else
-
1
HEADER = 'measurement,created_at,app,ruby,platform'
-
end
-
-
1
def with_output_file
-
fname = output_filename
-
-
if new = !File.exist?(fname)
-
FileUtils.mkdir_p(File.dirname(fname))
-
end
-
-
File.open(fname, 'ab') do |file|
-
file.puts(HEADER) if new
-
yield file
-
end
-
end
-
-
1
def output_filename
-
"#{super}.csv"
-
end
-
-
1
def rails_version
-
1
"rails-#{Rails::VERSION::STRING}#{rails_branch}"
-
end
-
-
1
def rails_branch
-
1
if File.directory?('vendor/rails/.git')
-
Dir.chdir('vendor/rails') do
-
".#{$1}.#{$2}" if `git branch -v` =~ /^\* (\S+)\s+(\S+)/
-
end
-
end
-
end
-
end
-
-
1
module Metrics
-
1
def self.[](name)
-
5
const_get(name.to_s.camelize)
-
rescue NameError
-
nil
-
end
-
-
1
class Base
-
1
include ActiveSupport::NumberHelper
-
-
1
attr_reader :total
-
-
1
def initialize
-
5
@total = 0
-
end
-
-
1
def name
-
@name ||= self.class.name.demodulize.underscore
-
end
-
-
1
def benchmark
-
with_gc_stats do
-
before = measure
-
yield
-
@total += (measure - before)
-
end
-
end
-
-
# overridden by each implementation.
-
1
def profile; end
-
-
1
protected
-
# overridden by each implementation.
-
1
def with_gc_stats; end
-
end
-
-
1
class Time < Base
-
1
def measure
-
::Time.now.to_f
-
end
-
-
1
def format(measurement)
-
6
if measurement < 1
-
4
'%d ms' % (measurement * 1000)
-
else
-
2
'%.2f sec' % measurement
-
end
-
end
-
end
-
-
1
class Amount < Base
-
1
def format(measurement)
-
3
number_to_delimited(measurement.floor)
-
end
-
end
-
-
1
class DigitalInformationUnit < Base
-
1
def format(measurement)
-
10
number_to_human_size(measurement, :precision => 2)
-
end
-
end
-
-
# each implementation provides its own metrics like ProcessTime, Memory or GcRuns
-
end
-
end
-
end
-
end
-
-
1
case RUBY_ENGINE
-
1
when 'ruby' then require 'active_support/testing/performance/ruby'
-
when 'rbx' then require 'active_support/testing/performance/rubinius'
-
when 'jruby' then require 'active_support/testing/performance/jruby'
-
else
-
$stderr.puts 'Your ruby interpreter is not supported for benchmarking.'
-
exit
-
end
-
1
begin
-
1
require 'ruby-prof'
-
rescue LoadError
-
$stderr.puts 'Specify ruby-prof as application\'s dependency in Gemfile to run benchmarks.'
-
raise
-
end
-
-
1
module ActiveSupport
-
1
module Testing
-
1
module Performance
-
1
DEFAULTS.merge!(
-
if ARGV.include?('--benchmark')
-
{ :metrics => [:wall_time, :memory, :objects, :gc_runs, :gc_time] }
-
else
-
{ :min_percent => 0.01,
-
:metrics => [:process_time, :memory, :objects],
-
1
:formats => [:flat, :graph_html, :call_tree, :call_stack] }
-
end).freeze
-
-
1
protected
-
1
remove_method :run_gc
-
1
def run_gc
-
GC.start
-
end
-
-
1
class Profiler < Performer
-
1
def initialize(*args)
-
super
-
@supported = @metric.measure_mode rescue false
-
end
-
-
1
remove_method :run
-
1
def run
-
return unless @supported
-
-
RubyProf.measure_mode = @metric.measure_mode
-
RubyProf.start
-
RubyProf.pause
-
full_profile_options[:runs].to_i.times { run_test(@metric, :profile) }
-
@data = RubyProf.stop
-
@total = @data.threads.sum(0) { |thread| thread.methods.max.total_time }
-
end
-
-
1
remove_method :record
-
1
def record
-
return unless @supported
-
-
klasses = full_profile_options[:formats].map { |f| RubyProf.const_get("#{f.to_s.camelize}Printer") }.compact
-
-
klasses.each do |klass|
-
fname = output_filename(klass)
-
FileUtils.mkdir_p(File.dirname(fname))
-
File.open(fname, 'wb') do |file|
-
klass.new(@data).print(file, full_profile_options.slice(:min_percent))
-
end
-
end
-
end
-
-
1
protected
-
1
def output_filename(printer_class)
-
suffix =
-
case printer_class.name.demodulize
-
when 'FlatPrinter'; 'flat.txt'
-
when 'FlatPrinterWithLineNumbers'; 'flat_line_numbers.txt'
-
when 'GraphPrinter'; 'graph.txt'
-
when 'GraphHtmlPrinter'; 'graph.html'
-
when 'GraphYamlPrinter'; 'graph.yml'
-
when 'CallTreePrinter'; 'tree.txt'
-
when 'CallStackPrinter'; 'stack.html'
-
when 'DotPrinter'; 'graph.dot'
-
else printer_class.name.sub(/Printer$/, '').underscore
-
end
-
-
"#{super()}_#{suffix}"
-
end
-
end
-
-
1
module Metrics
-
1
class Base
-
1
def measure_mode
-
self.class::Mode
-
end
-
-
1
remove_method :profile
-
1
def profile
-
RubyProf.resume
-
yield
-
ensure
-
RubyProf.pause
-
end
-
-
1
protected
-
1
remove_method :with_gc_stats
-
1
def with_gc_stats
-
GC::Profiler.enable
-
GC.start
-
yield
-
ensure
-
GC::Profiler.disable
-
end
-
end
-
-
1
class ProcessTime < Time
-
1
Mode = RubyProf::PROCESS_TIME if RubyProf.const_defined?(:PROCESS_TIME)
-
-
1
def measure
-
RubyProf.measure_process_time
-
end
-
end
-
-
1
class WallTime < Time
-
1
Mode = RubyProf::WALL_TIME if RubyProf.const_defined?(:WALL_TIME)
-
-
1
def measure
-
RubyProf.measure_wall_time
-
end
-
end
-
-
1
class CpuTime < Time
-
1
Mode = RubyProf::CPU_TIME if RubyProf.const_defined?(:CPU_TIME)
-
-
1
def initialize(*args)
-
# FIXME: yeah my CPU is 2.33 GHz
-
RubyProf.cpu_frequency = 2.33e9 unless RubyProf.cpu_frequency > 0
-
super
-
end
-
-
1
def measure
-
RubyProf.measure_cpu_time
-
end
-
end
-
-
1
class Memory < DigitalInformationUnit
-
1
Mode = RubyProf::MEMORY if RubyProf.const_defined?(:MEMORY)
-
-
# Ruby 1.9 + GCdata patch
-
1
if GC.respond_to?(:malloc_allocated_size)
-
def measure
-
GC.malloc_allocated_size
-
end
-
end
-
end
-
-
1
class Objects < Amount
-
1
Mode = RubyProf::ALLOCATIONS if RubyProf.const_defined?(:ALLOCATIONS)
-
-
# Ruby 1.9 + GCdata patch
-
1
if GC.respond_to?(:malloc_allocations)
-
def measure
-
GC.malloc_allocations
-
end
-
end
-
end
-
-
1
class GcRuns < Amount
-
1
Mode = RubyProf::GC_RUNS if RubyProf.const_defined?(:GC_RUNS)
-
-
1
def measure
-
GC.count
-
end
-
end
-
-
1
class GcTime < Time
-
1
Mode = RubyProf::GC_TIME if RubyProf.const_defined?(:GC_TIME)
-
-
1
def measure
-
GC::Profiler.total_time
-
end
-
end
-
end
-
end
-
end
-
end
-
1
require 'active_support/concern'
-
1
require 'active_support/callbacks'
-
-
1
module ActiveSupport
-
1
module Testing
-
1
module SetupAndTeardown
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
include ActiveSupport::Callbacks
-
1
define_callbacks :setup, :teardown
-
end
-
-
1
module ClassMethods
-
1
def setup(*args, &block)
-
7
set_callback(:setup, :before, *args, &block)
-
end
-
-
1
def teardown(*args, &block)
-
4
set_callback(:teardown, :after, *args, &block)
-
end
-
end
-
-
1
def before_setup
-
2858
super
-
2858
run_callbacks :setup
-
end
-
-
1
def after_teardown
-
2858
run_callbacks :teardown
-
2856
super
-
end
-
end
-
end
-
end
-
1
module ActiveSupport
-
1
module Testing
-
1
module TaggedLogging
-
1
attr_writer :tagged_logger
-
-
1
def before_setup
-
2858
tagged_logger.push_tags(self.class.name, __name__) if tagged_logging?
-
2858
super
-
end
-
-
1
def after_teardown
-
2856
super
-
2856
tagged_logger.pop_tags(2) if tagged_logging?
-
end
-
-
1
private
-
1
def tagged_logger
-
5719
@tagged_logger ||= (defined?(Rails.logger) && Rails.logger)
-
end
-
-
1
def tagged_logging?
-
5714
tagged_logger && tagged_logger.respond_to?(:push_tags)
-
end
-
end
-
end
-
end
-
1
require 'active_support'
-
-
1
module ActiveSupport
-
1
autoload :Duration, 'active_support/duration'
-
1
autoload :TimeWithZone, 'active_support/time_with_zone'
-
1
autoload :TimeZone, 'active_support/values/time_zone'
-
end
-
-
1
require 'date'
-
1
require 'time'
-
-
1
require 'active_support/core_ext/time/marshal'
-
1
require 'active_support/core_ext/time/acts_like'
-
1
require 'active_support/core_ext/time/calculations'
-
1
require 'active_support/core_ext/time/conversions'
-
1
require 'active_support/core_ext/time/zones'
-
-
1
require 'active_support/core_ext/date/acts_like'
-
1
require 'active_support/core_ext/date/calculations'
-
1
require 'active_support/core_ext/date/conversions'
-
1
require 'active_support/core_ext/date/zones'
-
-
1
require 'active_support/core_ext/date_time/acts_like'
-
1
require 'active_support/core_ext/date_time/calculations'
-
1
require 'active_support/core_ext/date_time/conversions'
-
1
require 'active_support/core_ext/date_time/zones'
-
-
1
require 'active_support/core_ext/integer/time'
-
1
require 'active_support/core_ext/numeric/time'
-
1
require 'active_support/values/time_zone'
-
1
require 'active_support/core_ext/object/acts_like'
-
-
1
module ActiveSupport
-
# A Time-like class that can represent a time in any time zone. Necessary
-
# because standard Ruby Time instances are limited to UTC and the
-
# system's <tt>ENV['TZ']</tt> zone.
-
#
-
# You shouldn't ever need to create a TimeWithZone instance directly via +new+.
-
# Instead use methods +local+, +parse+, +at+ and +now+ on TimeZone instances,
-
# and +in_time_zone+ on Time and DateTime instances.
-
#
-
# Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)'
-
# Time.zone.local(2007, 2, 10, 15, 30, 45) # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
# Time.zone.parse('2007-02-10 15:30:45') # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
# Time.zone.at(1170361845) # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
# Time.zone.now # => Sun, 18 May 2008 13:07:55 EDT -04:00
-
# Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone # => Sat, 10 Feb 2007 15:30:45 EST -05:00
-
#
-
# See Time and TimeZone for further documentation of these methods.
-
#
-
# TimeWithZone instances implement the same API as Ruby Time instances, so
-
# that Time and TimeWithZone instances are interchangeable.
-
#
-
# t = Time.zone.now # => Sun, 18 May 2008 13:27:25 EDT -04:00
-
# t.hour # => 13
-
# t.dst? # => true
-
# t.utc_offset # => -14400
-
# t.zone # => "EDT"
-
# t.to_s(:rfc822) # => "Sun, 18 May 2008 13:27:25 -0400"
-
# t + 1.day # => Mon, 19 May 2008 13:27:25 EDT -04:00
-
# t.beginning_of_year # => Tue, 01 Jan 2008 00:00:00 EST -05:00
-
# t > Time.utc(1999) # => true
-
# t.is_a?(Time) # => true
-
# t.is_a?(ActiveSupport::TimeWithZone) # => true
-
1
class TimeWithZone
-
-
# Report class name as 'Time' to thwart type checking.
-
1
def self.name
-
4
'Time'
-
end
-
-
1
include Comparable
-
1
attr_reader :time_zone
-
-
1
def initialize(utc_time, time_zone, local_time = nil, period = nil)
-
559
@utc, @time_zone, @time = utc_time, time_zone, local_time
-
559
@period = @utc ? period : get_period_and_ensure_valid_local_time
-
end
-
-
# Returns a Time or DateTime instance that represents the time in +time_zone+.
-
1
def time
-
462
@time ||= period.to_local(@utc)
-
end
-
-
# Returns a Time or DateTime instance that represents the time in UTC.
-
1
def utc
-
304
@utc ||= period.to_utc(@time)
-
end
-
1
alias_method :comparable_time, :utc
-
1
alias_method :getgm, :utc
-
1
alias_method :getutc, :utc
-
1
alias_method :gmtime, :utc
-
-
# Returns the underlying TZInfo::TimezonePeriod.
-
1
def period
-
641
@period ||= time_zone.period_for_utc(@utc)
-
end
-
-
# Returns the simultaneous time in <tt>Time.zone</tt>, or the specified zone.
-
1
def in_time_zone(new_zone = ::Time.zone)
-
6
return self if time_zone == new_zone
-
5
utc.in_time_zone(new_zone)
-
end
-
-
# Returns a <tt>Time.local()</tt> instance of the simultaneous time in your
-
# system's <tt>ENV['TZ']</tt> zone.
-
1
def localtime
-
2
utc.respond_to?(:getlocal) ? utc.getlocal : utc.to_time.getlocal
-
end
-
1
alias_method :getlocal, :localtime
-
-
1
def dst?
-
24
period.dst?
-
end
-
1
alias_method :isdst, :dst?
-
-
1
def utc?
-
220
time_zone.name == 'UTC'
-
end
-
1
alias_method :gmt?, :utc?
-
-
1
def utc_offset
-
223
period.utc_total_offset
-
end
-
1
alias_method :gmt_offset, :utc_offset
-
1
alias_method :gmtoff, :utc_offset
-
-
1
def formatted_offset(colon = true, alternate_utc_string = nil)
-
218
utc? && alternate_utc_string || TimeZone.seconds_to_utc_offset(utc_offset, colon)
-
end
-
-
# Time uses +zone+ to display the time zone abbreviation, so we're
-
# duck-typing it.
-
1
def zone
-
188
period.zone_identifier.to_s
-
end
-
-
1
def inspect
-
161
"#{time.strftime('%a, %d %b %Y %H:%M:%S')} #{zone} #{formatted_offset}"
-
end
-
-
1
def xmlschema(fraction_digits = 0)
-
11
fraction = if fraction_digits > 0
-
6
(".%06i" % time.usec)[0, fraction_digits + 1]
-
end
-
-
11
"#{time.strftime("%Y-%m-%dT%H:%M:%S")}#{fraction}#{formatted_offset(true, 'Z')}"
-
end
-
1
alias_method :iso8601, :xmlschema
-
-
# Coerces time to a string for JSON encoding. The default format is ISO 8601.
-
# You can get %Y/%m/%d %H:%M:%S +offset style by setting
-
# <tt>ActiveSupport::JSON::Encoding.use_standard_json_time_format</tt>
-
# to +false+.
-
#
-
# # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = true
-
# Time.utc(2005,2,1,15,15,10).in_time_zone.to_json
-
# # => "2005-02-01T15:15:10Z"
-
#
-
# # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = false
-
# Time.utc(2005,2,1,15,15,10).in_time_zone.to_json
-
# # => "2005/02/01 15:15:10 +0000"
-
1
def as_json(options = nil)
-
2
if ActiveSupport::JSON::Encoding.use_standard_json_time_format
-
1
xmlschema
-
else
-
1
%(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
-
end
-
end
-
-
1
def encode_with(coder)
-
2
if coder.respond_to?(:represent_object)
-
2
coder.represent_object(nil, utc)
-
else
-
coder.represent_scalar(nil, utc.strftime("%Y-%m-%d %H:%M:%S.%9NZ"))
-
end
-
end
-
-
1
def httpdate
-
1
utc.httpdate
-
end
-
-
1
def rfc2822
-
1
to_s(:rfc822)
-
end
-
1
alias_method :rfc822, :rfc2822
-
-
# <tt>:db</tt> format outputs time in UTC; all others output time in local.
-
# Uses TimeWithZone's +strftime+, so <tt>%Z</tt> and <tt>%z</tt> work correctly.
-
1
def to_s(format = :default)
-
29
if format == :db
-
1
utc.to_s(format)
-
28
elsif formatter = ::Time::DATE_FORMATS[format]
-
1
formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
-
else
-
27
"#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby 1.9 Time#to_s format
-
end
-
end
-
1
alias_method :to_formatted_s, :to_s
-
-
# Replaces <tt>%Z</tt> and <tt>%z</tt> directives with +zone+ and
-
# +formatted_offset+, respectively, before passing to Time#strftime, so
-
# that zone information is correct
-
1
def strftime(format)
-
5
format = format.gsub('%Z', zone)
-
.gsub('%z', formatted_offset(false))
-
.gsub('%:z', formatted_offset(true))
-
.gsub('%::z', formatted_offset(true) + ":00")
-
5
time.strftime(format)
-
end
-
-
# Use the time in UTC for comparisons.
-
1
def <=>(other)
-
45
utc <=> other
-
end
-
-
1
def between?(min, max)
-
2
utc.between?(min, max)
-
end
-
-
1
def past?
-
6
utc.past?
-
end
-
-
1
def today?
-
4
time.today?
-
end
-
-
1
def future?
-
6
utc.future?
-
end
-
-
1
def eql?(other)
-
4
utc.eql?(other)
-
end
-
-
1
def hash
-
2
utc.hash
-
end
-
-
1
def +(other)
-
# If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
-
# otherwise move forward from #utc, for accuracy when moving across DST boundaries
-
35
if duration_of_variable_length?(other)
-
13
method_missing(:+, other)
-
else
-
22
result = utc.acts_like?(:date) ? utc.since(other) : utc + other rescue utc.since(other)
-
22
result.in_time_zone(time_zone)
-
end
-
end
-
-
1
def -(other)
-
# If we're subtracting a Duration of variable length (i.e., years, months, days), move backwards from #time,
-
# otherwise move backwards #utc, for accuracy when moving across DST boundaries
-
28
if other.acts_like?(:time)
-
6
utc.to_f - other.to_f
-
22
elsif duration_of_variable_length?(other)
-
7
method_missing(:-, other)
-
else
-
15
result = utc.acts_like?(:date) ? utc.ago(other) : utc - other rescue utc.ago(other)
-
15
result.in_time_zone(time_zone)
-
end
-
end
-
-
1
def since(other)
-
# If we're adding a Duration of variable length (i.e., years, months, days), move forward from #time,
-
# otherwise move forward from #utc, for accuracy when moving across DST boundaries
-
46
if duration_of_variable_length?(other)
-
16
method_missing(:since, other)
-
else
-
30
utc.since(other).in_time_zone(time_zone)
-
end
-
end
-
-
1
def ago(other)
-
15
since(-other)
-
end
-
-
1
def advance(options)
-
# If we're advancing a value of variable length (i.e., years, weeks, months, days), advance from #time,
-
# otherwise advance from #utc, for accuracy when moving across DST boundaries
-
35
if options.values_at(:years, :weeks, :months, :days).any?
-
19
method_missing(:advance, options)
-
else
-
16
utc.advance(options).in_time_zone(time_zone)
-
end
-
end
-
-
1
%w(year mon month day mday wday yday hour min sec to_date).each do |method_name|
-
11
class_eval <<-EOV, __FILE__, __LINE__ + 1
-
def #{method_name} # def month
-
time.#{method_name} # time.month
-
end # end
-
EOV
-
end
-
-
1
def usec
-
2
time.respond_to?(:usec) ? time.usec : 0
-
end
-
-
1
def to_a
-
8
[time.sec, time.min, time.hour, time.day, time.mon, time.year, time.wday, time.yday, dst?, zone]
-
end
-
-
1
def to_f
-
5
utc.to_f
-
end
-
-
1
def to_i
-
2
utc.to_i
-
end
-
1
alias_method :tv_sec, :to_i
-
-
# A TimeWithZone acts like a Time, so just return +self+.
-
1
def to_time
-
60
utc
-
end
-
-
1
def to_datetime
-
5
utc.to_datetime.new_offset(Rational(utc_offset, 86_400))
-
end
-
-
# So that +self+ <tt>acts_like?(:time)</tt>.
-
1
def acts_like_time?
-
true
-
end
-
-
# Say we're a Time to thwart type checking.
-
1
def is_a?(klass)
-
74
klass == ::Time || super
-
end
-
1
alias_method :kind_of?, :is_a?
-
-
1
def freeze
-
2
period; utc; time # preload instance variables before freezing
-
2
super
-
end
-
-
1
def marshal_dump
-
2
[utc, time_zone.name, time]
-
end
-
-
1
def marshal_load(variables)
-
2
initialize(variables[0].utc, ::Time.find_zone(variables[1]), variables[2].utc)
-
end
-
-
# Ensure proxy class responds to all methods that underlying time instance
-
# responds to.
-
1
def respond_to_missing?(sym, include_priv)
-
# consistently respond false to acts_like?(:date), regardless of whether #time is a Time or DateTime
-
18
return false if sym.to_sym == :acts_like_date?
-
16
time.respond_to?(sym, include_priv)
-
end
-
-
# Send the missing method to +time+ instance, and wrap result in a new
-
# TimeWithZone with the existing +time_zone+.
-
1
def method_missing(sym, *args, &block)
-
106
wrap_with_time_zone time.__send__(sym, *args, &block)
-
end
-
-
1
private
-
1
def get_period_and_ensure_valid_local_time
-
# we don't want a Time.local instance enforcing its own DST rules as well,
-
# so transfer time values to a utc constructor if necessary
-
185
@time = transfer_time_values_to_utc_constructor(@time) unless @time.utc?
-
185
begin
-
193
@time_zone.period_for_local(@time)
-
8
rescue ::TZInfo::PeriodNotFound
-
# time is in the "spring forward" hour gap, so we're moving the time forward one hour and trying again
-
8
@time += 1.hour
-
8
retry
-
end
-
end
-
-
1
def transfer_time_values_to_utc_constructor(time)
-
50
::Time.utc_time(time.year, time.month, time.day, time.hour, time.min, time.sec, time.respond_to?(:nsec) ? Rational(time.nsec, 1000) : 0)
-
end
-
-
1
def duration_of_variable_length?(obj)
-
167
ActiveSupport::Duration === obj && obj.parts.any? {|p| [:years, :months, :days].include?(p[0]) }
-
end
-
-
1
def wrap_with_time_zone(time)
-
110
if time.acts_like?(:time)
-
90
self.class.new(nil, time_zone, time)
-
20
elsif time.is_a?(Range)
-
2
wrap_with_time_zone(time.begin)..wrap_with_time_zone(time.end)
-
else
-
18
time
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'active_support/core_ext/object/try'
-
-
1
module ActiveSupport
-
# The TimeZone class serves as a wrapper around TZInfo::Timezone instances.
-
# It allows us to do the following:
-
#
-
# * Limit the set of zones provided by TZInfo to a meaningful subset of 142
-
# zones.
-
# * Retrieve and display zones with a friendlier name
-
# (e.g., "Eastern Time (US & Canada)" instead of "America/New_York").
-
# * Lazily load TZInfo::Timezone instances only when they're needed.
-
# * Create ActiveSupport::TimeWithZone instances via TimeZone's +local+,
-
# +parse+, +at+ and +now+ methods.
-
#
-
# If you set <tt>config.time_zone</tt> in the Rails Application, you can
-
# access this TimeZone object via <tt>Time.zone</tt>:
-
#
-
# # application.rb:
-
# class Application < Rails::Application
-
# config.time_zone = 'Eastern Time (US & Canada)'
-
# end
-
#
-
# Time.zone # => #<TimeZone:0x514834...>
-
# Time.zone.name # => "Eastern Time (US & Canada)"
-
# Time.zone.now # => Sun, 18 May 2008 14:30:44 EDT -04:00
-
#
-
# The version of TZInfo bundled with Active Support only includes the
-
# definitions necessary to support the zones defined by the TimeZone class.
-
# If you need to use zones that aren't defined by TimeZone, you'll need to
-
# install the TZInfo gem (if a recent version of the gem is installed locally,
-
# this will be used instead of the bundled version.)
-
1
class TimeZone
-
# Keys are Rails TimeZone names, values are TZInfo identifiers.
-
1
MAPPING = {
-
"International Date Line West" => "Pacific/Midway",
-
"Midway Island" => "Pacific/Midway",
-
"American Samoa" => "Pacific/Pago_Pago",
-
"Hawaii" => "Pacific/Honolulu",
-
"Alaska" => "America/Juneau",
-
"Pacific Time (US & Canada)" => "America/Los_Angeles",
-
"Tijuana" => "America/Tijuana",
-
"Mountain Time (US & Canada)" => "America/Denver",
-
"Arizona" => "America/Phoenix",
-
"Chihuahua" => "America/Chihuahua",
-
"Mazatlan" => "America/Mazatlan",
-
"Central Time (US & Canada)" => "America/Chicago",
-
"Saskatchewan" => "America/Regina",
-
"Guadalajara" => "America/Mexico_City",
-
"Mexico City" => "America/Mexico_City",
-
"Monterrey" => "America/Monterrey",
-
"Central America" => "America/Guatemala",
-
"Eastern Time (US & Canada)" => "America/New_York",
-
"Indiana (East)" => "America/Indiana/Indianapolis",
-
"Bogota" => "America/Bogota",
-
"Lima" => "America/Lima",
-
"Quito" => "America/Lima",
-
"Atlantic Time (Canada)" => "America/Halifax",
-
"Caracas" => "America/Caracas",
-
"La Paz" => "America/La_Paz",
-
"Santiago" => "America/Santiago",
-
"Newfoundland" => "America/St_Johns",
-
"Brasilia" => "America/Sao_Paulo",
-
"Buenos Aires" => "America/Argentina/Buenos_Aires",
-
"Georgetown" => "America/Guyana",
-
"Greenland" => "America/Godthab",
-
"Mid-Atlantic" => "Atlantic/South_Georgia",
-
"Azores" => "Atlantic/Azores",
-
"Cape Verde Is." => "Atlantic/Cape_Verde",
-
"Dublin" => "Europe/Dublin",
-
"Edinburgh" => "Europe/London",
-
"Lisbon" => "Europe/Lisbon",
-
"London" => "Europe/London",
-
"Casablanca" => "Africa/Casablanca",
-
"Monrovia" => "Africa/Monrovia",
-
"UTC" => "Etc/UTC",
-
"Belgrade" => "Europe/Belgrade",
-
"Bratislava" => "Europe/Bratislava",
-
"Budapest" => "Europe/Budapest",
-
"Ljubljana" => "Europe/Ljubljana",
-
"Prague" => "Europe/Prague",
-
"Sarajevo" => "Europe/Sarajevo",
-
"Skopje" => "Europe/Skopje",
-
"Warsaw" => "Europe/Warsaw",
-
"Zagreb" => "Europe/Zagreb",
-
"Brussels" => "Europe/Brussels",
-
"Copenhagen" => "Europe/Copenhagen",
-
"Madrid" => "Europe/Madrid",
-
"Paris" => "Europe/Paris",
-
"Amsterdam" => "Europe/Amsterdam",
-
"Berlin" => "Europe/Berlin",
-
"Bern" => "Europe/Berlin",
-
"Rome" => "Europe/Rome",
-
"Stockholm" => "Europe/Stockholm",
-
"Vienna" => "Europe/Vienna",
-
"West Central Africa" => "Africa/Algiers",
-
"Bucharest" => "Europe/Bucharest",
-
"Cairo" => "Africa/Cairo",
-
"Helsinki" => "Europe/Helsinki",
-
"Kyiv" => "Europe/Kiev",
-
"Riga" => "Europe/Riga",
-
"Sofia" => "Europe/Sofia",
-
"Tallinn" => "Europe/Tallinn",
-
"Vilnius" => "Europe/Vilnius",
-
"Athens" => "Europe/Athens",
-
"Istanbul" => "Europe/Istanbul",
-
"Minsk" => "Europe/Minsk",
-
"Jerusalem" => "Asia/Jerusalem",
-
"Harare" => "Africa/Harare",
-
"Pretoria" => "Africa/Johannesburg",
-
"Moscow" => "Europe/Moscow",
-
"St. Petersburg" => "Europe/Moscow",
-
"Volgograd" => "Europe/Moscow",
-
"Kuwait" => "Asia/Kuwait",
-
"Riyadh" => "Asia/Riyadh",
-
"Nairobi" => "Africa/Nairobi",
-
"Baghdad" => "Asia/Baghdad",
-
"Tehran" => "Asia/Tehran",
-
"Abu Dhabi" => "Asia/Muscat",
-
"Muscat" => "Asia/Muscat",
-
"Baku" => "Asia/Baku",
-
"Tbilisi" => "Asia/Tbilisi",
-
"Yerevan" => "Asia/Yerevan",
-
"Kabul" => "Asia/Kabul",
-
"Ekaterinburg" => "Asia/Yekaterinburg",
-
"Islamabad" => "Asia/Karachi",
-
"Karachi" => "Asia/Karachi",
-
"Tashkent" => "Asia/Tashkent",
-
"Chennai" => "Asia/Kolkata",
-
"Kolkata" => "Asia/Kolkata",
-
"Mumbai" => "Asia/Kolkata",
-
"New Delhi" => "Asia/Kolkata",
-
"Kathmandu" => "Asia/Kathmandu",
-
"Astana" => "Asia/Dhaka",
-
"Dhaka" => "Asia/Dhaka",
-
"Sri Jayawardenepura" => "Asia/Colombo",
-
"Almaty" => "Asia/Almaty",
-
"Novosibirsk" => "Asia/Novosibirsk",
-
"Rangoon" => "Asia/Rangoon",
-
"Bangkok" => "Asia/Bangkok",
-
"Hanoi" => "Asia/Bangkok",
-
"Jakarta" => "Asia/Jakarta",
-
"Krasnoyarsk" => "Asia/Krasnoyarsk",
-
"Beijing" => "Asia/Shanghai",
-
"Chongqing" => "Asia/Chongqing",
-
"Hong Kong" => "Asia/Hong_Kong",
-
"Urumqi" => "Asia/Urumqi",
-
"Kuala Lumpur" => "Asia/Kuala_Lumpur",
-
"Singapore" => "Asia/Singapore",
-
"Taipei" => "Asia/Taipei",
-
"Perth" => "Australia/Perth",
-
"Irkutsk" => "Asia/Irkutsk",
-
"Ulaan Bataar" => "Asia/Ulaanbaatar",
-
"Seoul" => "Asia/Seoul",
-
"Osaka" => "Asia/Tokyo",
-
"Sapporo" => "Asia/Tokyo",
-
"Tokyo" => "Asia/Tokyo",
-
"Yakutsk" => "Asia/Yakutsk",
-
"Darwin" => "Australia/Darwin",
-
"Adelaide" => "Australia/Adelaide",
-
"Canberra" => "Australia/Melbourne",
-
"Melbourne" => "Australia/Melbourne",
-
"Sydney" => "Australia/Sydney",
-
"Brisbane" => "Australia/Brisbane",
-
"Hobart" => "Australia/Hobart",
-
"Vladivostok" => "Asia/Vladivostok",
-
"Guam" => "Pacific/Guam",
-
"Port Moresby" => "Pacific/Port_Moresby",
-
"Magadan" => "Asia/Magadan",
-
"Solomon Is." => "Pacific/Guadalcanal",
-
"New Caledonia" => "Pacific/Noumea",
-
"Fiji" => "Pacific/Fiji",
-
"Kamchatka" => "Asia/Kamchatka",
-
"Marshall Is." => "Pacific/Majuro",
-
"Auckland" => "Pacific/Auckland",
-
"Wellington" => "Pacific/Auckland",
-
"Nuku'alofa" => "Pacific/Tongatapu",
-
"Tokelau Is." => "Pacific/Fakaofo",
-
"Samoa" => "Pacific/Apia"
-
}
-
-
1
UTC_OFFSET_WITH_COLON = '%s%02d:%02d'
-
1
UTC_OFFSET_WITHOUT_COLON = UTC_OFFSET_WITH_COLON.sub(':', '')
-
-
# Assumes self represents an offset from UTC in seconds (as returned from
-
# Time#utc_offset) and turns this into an +HH:MM formatted string.
-
#
-
# TimeZone.seconds_to_utc_offset(-21_600) # => "-06:00"
-
1
def self.seconds_to_utc_offset(seconds, colon = true)
-
252
format = colon ? UTC_OFFSET_WITH_COLON : UTC_OFFSET_WITHOUT_COLON
-
252
sign = (seconds < 0 ? '-' : '+')
-
252
hours = seconds.abs / 3600
-
252
minutes = (seconds.abs % 3600) / 60
-
252
format % [sign, hours, minutes]
-
end
-
-
1
include Comparable
-
1
attr_reader :name
-
1
attr_reader :tzinfo
-
-
# Create a new TimeZone object with the given name and offset. The
-
# offset is the number of seconds that this time zone is offset from UTC
-
# (GMT). Seconds were chosen as the offset unit because that is the unit
-
# that Ruby uses to represent time zone offsets (see Time#utc_offset).
-
1
def initialize(name, utc_offset = nil, tzinfo = nil)
-
305
self.class.send(:require_tzinfo)
-
-
305
@name = name
-
305
@utc_offset = utc_offset
-
305
@tzinfo = tzinfo || TimeZone.find_tzinfo(name)
-
305
@current_period = nil
-
end
-
-
# Returns the offset of this time zone from UTC in seconds.
-
1
def utc_offset
-
4799
if @utc_offset
-
1
@utc_offset
-
else
-
4798
@current_period ||= tzinfo.try(:current_period)
-
4787
@current_period.try(:utc_offset)
-
end
-
end
-
-
# Returns the offset of this time zone as a formatted string, of the
-
# format "+HH:MM".
-
1
def formatted_offset(colon=true, alternate_utc_string = nil)
-
7
utc_offset == 0 && alternate_utc_string || self.class.seconds_to_utc_offset(utc_offset, colon)
-
end
-
-
# Compare this time zone to the parameter. The two are compared first on
-
# their offsets, and then by name.
-
1
def <=>(zone)
-
984
result = (utc_offset <=> zone.utc_offset)
-
980
result = (name <=> zone.name) if result == 0
-
980
result
-
end
-
-
# Compare #name and TZInfo identifier to a supplied regexp, returning +true+
-
# if a match is found.
-
1
def =~(re)
-
3
return true if name =~ re || MAPPING[name] =~ re
-
end
-
-
# Returns a textual representation of this time zone.
-
1
def to_s
-
1
"(GMT#{formatted_offset}) #{name}"
-
end
-
-
# Method for creating new ActiveSupport::TimeWithZone instance in time zone
-
# of +self+ from given values.
-
#
-
# Time.zone = 'Hawaii' # => "Hawaii"
-
# Time.zone.local(2007, 2, 1, 15, 30, 45) # => Thu, 01 Feb 2007 15:30:45 HST -10:00
-
1
def local(*args)
-
21
time = Time.utc_time(*args)
-
21
ActiveSupport::TimeWithZone.new(nil, self, time)
-
end
-
-
# Method for creating new ActiveSupport::TimeWithZone instance in time zone
-
# of +self+ from number of seconds since the Unix epoch.
-
#
-
# Time.zone = 'Hawaii' # => "Hawaii"
-
# Time.utc(2000).to_f # => 946684800.0
-
# Time.zone.at(946684800.0) # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
1
def at(secs)
-
2
Time.at(secs).utc.in_time_zone(self)
-
end
-
-
# Method for creating new ActiveSupport::TimeWithZone instance in time zone
-
# of +self+ from parsed string.
-
#
-
# Time.zone = 'Hawaii' # => "Hawaii"
-
# Time.zone.parse('1999-12-31 14:00:00') # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
#
-
# If upper components are missing from the string, they are supplied from
-
# TimeZone#now:
-
#
-
# Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
# Time.zone.parse('22:30:00') # => Fri, 31 Dec 1999 22:30:00 HST -10:00
-
1
def parse(str, now=now)
-
58
date_parts = Date._parse(str)
-
58
return if date_parts.empty?
-
56
time = Time.parse(str, now) rescue DateTime.parse(str)
-
-
56
if date_parts[:offset].nil?
-
30
if date_parts[:hour] && time.hour != date_parts[:hour]
-
1
time = DateTime.parse(str)
-
end
-
-
30
ActiveSupport::TimeWithZone.new(nil, self, time)
-
else
-
26
time.in_time_zone(self)
-
end
-
end
-
-
# Returns an ActiveSupport::TimeWithZone instance representing the current
-
# time in the time zone represented by +self+.
-
#
-
# Time.zone = 'Hawaii' # => "Hawaii"
-
# Time.zone.now # => Wed, 23 Jan 2008 20:24:27 HST -10:00
-
1
def now
-
80
time_now.utc.in_time_zone(self)
-
end
-
-
# Return the current date in this time zone.
-
1
def today
-
8
tzinfo.now.to_date
-
end
-
-
# Adjust the given time to the simultaneous time in the time zone
-
# represented by +self+. Returns a Time.utc() instance -- if you want an
-
# ActiveSupport::TimeWithZone instance, use Time#in_time_zone() instead.
-
1
def utc_to_local(time)
-
4
tzinfo.utc_to_local(time)
-
end
-
-
# Adjust the given time to the simultaneous time in UTC. Returns a
-
# Time.utc() instance.
-
1
def local_to_utc(time, dst=true)
-
2
tzinfo.local_to_utc(time, dst)
-
end
-
-
# Available so that TimeZone instances respond like TZInfo::Timezone
-
# instances.
-
1
def period_for_utc(time)
-
148
tzinfo.period_for_utc(time)
-
end
-
-
# Available so that TimeZone instances respond like TZInfo::Timezone
-
# instances.
-
1
def period_for_local(time, dst=true)
-
194
tzinfo.period_for_local(time, dst)
-
end
-
-
1
def self.find_tzinfo(name)
-
316
TZInfo::TimezoneProxy.new(MAPPING[name] || name)
-
end
-
-
1
class << self
-
1
alias_method :create, :new
-
-
# Return a TimeZone instance with the given name, or +nil+ if no
-
# such TimeZone instance exists. (This exists to support the use of
-
# this class with the +composed_of+ macro.)
-
1
def new(name)
-
1
self[name]
-
end
-
-
# Return an array of all TimeZone objects. There are multiple
-
# TimeZone objects per time zone, in many cases, to make it easier
-
# for users to find their own time zone.
-
1
def all
-
40
@zones ||= zones_map.values.sort
-
end
-
-
1
def zones_map
-
@zones_map ||= begin
-
1
new_zones_names = MAPPING.keys - lazy_zones_map.keys
-
145
new_zones = Hash[new_zones_names.map { |place| [place, create(place)] }]
-
-
1
lazy_zones_map.merge(new_zones)
-
2
end
-
end
-
-
# Locate a specific time zone object. If the argument is a string, it
-
# is interpreted to mean the name of the timezone to locate. If it is a
-
# numeric value it is either the hour offset, or the second offset, of the
-
# timezone to find. (The first one with that offset will be returned.)
-
# Returns +nil+ if no such time zone is known to the system.
-
1
def [](arg)
-
589
case arg
-
when String
-
544
begin
-
557
lazy_zones_map[arg] ||= lookup(arg).tap { |tz| tz.utc_offset }
-
10
rescue TZInfo::InvalidTimezoneIdentifier
-
10
nil
-
end
-
when Numeric, ActiveSupport::Duration
-
37
arg *= 3600 if arg.abs <= 13
-
2697
all.find { |z| z.utc_offset == arg.to_i }
-
else
-
8
raise ArgumentError, "invalid argument to TimeZone[]: #{arg.inspect}"
-
end
-
end
-
-
# A convenience method for returning a collection of TimeZone objects
-
# for time zones in the USA.
-
1
def us_zones
-
146
@us_zones ||= all.find_all { |z| z.name =~ /US|Arizona|Indiana|Hawaii|Alaska/ }
-
end
-
-
1
protected
-
-
1
def require_tzinfo
-
851
require 'tzinfo' unless defined?(::TZInfo)
-
rescue LoadError
-
$stderr.puts "You don't have tzinfo installed in your application. Please add it to your Gemfile and run bundle install"
-
raise
-
end
-
-
1
private
-
-
1
def lookup(name)
-
13
(tzinfo = find_tzinfo(name)) && create(tzinfo.name.freeze)
-
end
-
-
1
def lazy_zones_map
-
546
require_tzinfo
-
-
@lazy_zones_map ||= Hash.new do |hash, place|
-
157
hash[place] = create(place) if MAPPING.has_key?(place)
-
546
end
-
end
-
end
-
-
1
private
-
-
1
def time_now
-
72
Time.now
-
end
-
end
-
end
-
1
module ActiveSupport
-
1
module VERSION #:nodoc:
-
1
MAJOR = 4
-
1
MINOR = 0
-
1
TINY = 0
-
1
PRE = "beta"
-
-
1
STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
-
end
-
end
-
1
require 'time'
-
1
require 'base64'
-
1
require 'active_support/core_ext/module/delegation'
-
1
require 'active_support/core_ext/string/inflections'
-
-
1
module ActiveSupport
-
# = XmlMini
-
#
-
# To use the much faster libxml parser:
-
# gem 'libxml-ruby', '=0.9.7'
-
# XmlMini.backend = 'LibXML'
-
1
module XmlMini
-
1
extend self
-
-
# This module decorates files deserialized using Hash.from_xml with
-
# the <tt>original_filename</tt> and <tt>content_type</tt> methods.
-
1
module FileLike #:nodoc:
-
1
attr_writer :original_filename, :content_type
-
-
1
def original_filename
-
4
@original_filename || 'untitled'
-
end
-
-
1
def content_type
-
4
@content_type || 'application/octet-stream'
-
end
-
end
-
-
DEFAULT_ENCODINGS = {
-
"binary" => "base64"
-
1
} unless defined?(DEFAULT_ENCODINGS)
-
-
TYPE_NAMES = {
-
"Symbol" => "symbol",
-
"Fixnum" => "integer",
-
"Bignum" => "integer",
-
"BigDecimal" => "decimal",
-
"Float" => "float",
-
"TrueClass" => "boolean",
-
"FalseClass" => "boolean",
-
"Date" => "date",
-
"DateTime" => "dateTime",
-
"Time" => "dateTime",
-
"Array" => "array",
-
"Hash" => "hash"
-
1
} unless defined?(TYPE_NAMES)
-
-
FORMATTING = {
-
1
"symbol" => Proc.new { |symbol| symbol.to_s },
-
1
"date" => Proc.new { |date| date.to_s(:db) },
-
2
"dateTime" => Proc.new { |time| time.xmlschema },
-
"binary" => Proc.new { |binary| ::Base64.encode64(binary) },
-
"yaml" => Proc.new { |yaml| yaml.to_yaml }
-
1
} unless defined?(FORMATTING)
-
-
# TODO use regexp instead of Date.parse
-
1
unless defined?(PARSING)
-
1
PARSING = {
-
1
"symbol" => Proc.new { |symbol| symbol.to_sym },
-
5
"date" => Proc.new { |date| ::Date.parse(date) },
-
9
"datetime" => Proc.new { |time| Time.xmlschema(time).utc rescue ::DateTime.parse(time).utc },
-
15
"integer" => Proc.new { |integer| integer.to_i },
-
3
"float" => Proc.new { |float| float.to_f },
-
2
"decimal" => Proc.new { |number| BigDecimal(number) },
-
6
"boolean" => Proc.new { |boolean| %w(1 true).include?(boolean.strip) },
-
"string" => Proc.new { |string| string.to_s },
-
1
"yaml" => Proc.new { |yaml| YAML::load(yaml) rescue yaml },
-
1
"base64Binary" => Proc.new { |bin| ::Base64.decode64(bin) },
-
1
"binary" => Proc.new { |bin, entity| _parse_binary(bin, entity) },
-
4
"file" => Proc.new { |file, entity| _parse_file(file, entity) }
-
}
-
-
1
PARSING.update(
-
"double" => PARSING["float"],
-
"dateTime" => PARSING["datetime"]
-
)
-
end
-
-
1
attr_reader :backend
-
1
delegate :parse, :to => :backend
-
-
1
def backend=(name)
-
137
if name.is_a?(Module)
-
66
@backend = name
-
else
-
71
require "active_support/xml_mini/#{name.downcase}"
-
71
@backend = ActiveSupport.const_get("XmlMini_#{name}")
-
end
-
end
-
-
1
def with_backend(name)
-
28
old_backend, self.backend = backend, name
-
28
yield
-
ensure
-
28
self.backend = old_backend
-
end
-
-
1
def to_tag(key, value, options)
-
108
type_name = options.delete(:type)
-
108
merged_options = options.merge(:root => key, :skip_instruct => true)
-
-
108
if value.is_a?(::Method) || value.is_a?(::Proc)
-
2
if value.arity == 1
-
1
value.call(merged_options)
-
else
-
1
value.call(merged_options, key.to_s.singularize)
-
end
-
106
elsif value.respond_to?(:to_xml)
-
27
value.to_xml(merged_options)
-
else
-
79
type_name ||= TYPE_NAMES[value.class.name]
-
79
type_name ||= value.class.name if value && !value.respond_to?(:to_str)
-
79
type_name = type_name.to_s if type_name
-
79
type_name = "dateTime" if type_name == "datetime"
-
-
79
key = rename_key(key.to_s, options)
-
-
79
attributes = options[:skip_types] || type_name.nil? ? { } : { :type => type_name }
-
79
attributes[:nil] = true if value.nil?
-
-
79
encoding = options[:encoding] || DEFAULT_ENCODINGS[type_name]
-
79
attributes[:encoding] = encoding if encoding
-
-
79
formatted_value = FORMATTING[type_name] && !value.nil? ?
-
FORMATTING[type_name].call(value) : value
-
-
79
options[:builder].tag!(key, formatted_value, attributes)
-
end
-
end
-
-
1
def rename_key(key, options = {})
-
143
camelize = options[:camelize]
-
143
dasherize = !options.has_key?(:dasherize) || options[:dasherize]
-
143
if camelize
-
9
key = true == camelize ? key.camelize : key.camelize(camelize)
-
end
-
143
key = _dasherize(key) if dasherize
-
143
key
-
end
-
-
1
protected
-
-
1
def _dasherize(key)
-
# $2 must be a non-greedy regex for this to work
-
132
left, middle, right = /\A(_*)(.*?)(_*)\Z/.match(key.strip)[1,3]
-
132
"#{left}#{middle.tr('_ ', '--')}#{right}"
-
end
-
-
# TODO: Add support for other encodings
-
1
def _parse_binary(bin, entity) #:nodoc:
-
1
case entity['encoding']
-
when 'base64'
-
1
::Base64.decode64(bin)
-
else
-
bin
-
end
-
end
-
-
1
def _parse_file(file, entity)
-
4
f = StringIO.new(::Base64.decode64(file))
-
4
f.extend(FileLike)
-
4
f.original_filename = entity['name']
-
4
f.content_type = entity['content_type']
-
4
f
-
end
-
end
-
-
1
XmlMini.backend = 'REXML'
-
end
-
1
begin
-
1
require 'nokogiri'
-
rescue LoadError => e
-
$stderr.puts "You don't have nokogiri installed in your application. Please add it to your Gemfile and run bundle install"
-
raise e
-
end
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'stringio'
-
-
1
module ActiveSupport
-
1
module XmlMini_Nokogiri #:nodoc:
-
1
extend self
-
-
# Parse an XML Document string or IO into a simple hash using libxml / nokogiri.
-
# data::
-
# XML Document string or IO to parse
-
1
def parse(data)
-
19
if !data.respond_to?(:read)
-
18
data = StringIO.new(data || '')
-
end
-
-
19
char = data.getc
-
19
if char.nil?
-
2
{}
-
else
-
17
data.ungetc(char)
-
17
doc = Nokogiri::XML(data)
-
17
raise doc.errors.first if doc.errors.length > 0
-
16
doc.to_hash
-
end
-
end
-
-
1
module Conversions #:nodoc:
-
1
module Document #:nodoc:
-
1
def to_hash
-
16
root.to_hash
-
end
-
end
-
-
1
module Node #:nodoc:
-
1
CONTENT_ROOT = '__content__'.freeze
-
-
# Convert XML document to hash.
-
#
-
# hash::
-
# Hash to merge the converted element into.
-
1
def to_hash(hash={})
-
33
node_hash = {}
-
-
# Insert node hash into parent hash correctly.
-
33
case hash[name]
-
when Array then hash[name] << node_hash
-
2
when Hash then hash[name] = [hash[name], node_hash]
-
31
when nil then hash[name] = node_hash
-
end
-
-
# Handle child elements
-
33
children.each do |c|
-
67
if c.element?
-
17
c.to_hash(node_hash)
-
elsif c.text? || c.cdata?
-
50
node_hash[CONTENT_ROOT] ||= ''
-
50
node_hash[CONTENT_ROOT] << c.content
-
end
-
end
-
-
# Remove content node if it is blank and there are child tags
-
33
if node_hash.length > 1 && node_hash[CONTENT_ROOT].blank?
-
13
node_hash.delete(CONTENT_ROOT)
-
end
-
-
# Handle attributes
-
47
attribute_nodes.each { |a| node_hash[a.node_name] = a.value }
-
-
33
hash
-
end
-
end
-
end
-
-
1
Nokogiri::XML::Document.send(:include, Conversions::Document)
-
1
Nokogiri::XML::Node.send(:include, Conversions::Node)
-
end
-
end
-
1
begin
-
1
require 'nokogiri'
-
rescue LoadError => e
-
$stderr.puts "You don't have nokogiri installed in your application. Please add it to your Gemfile and run bundle install"
-
raise e
-
end
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'stringio'
-
-
1
module ActiveSupport
-
1
module XmlMini_NokogiriSAX #:nodoc:
-
1
extend self
-
-
# Class that will build the hash while the XML document
-
# is being parsed using SAX events.
-
1
class HashBuilder < Nokogiri::XML::SAX::Document
-
-
1
CONTENT_KEY = '__content__'.freeze
-
1
HASH_SIZE_KEY = '__hash_size__'.freeze
-
-
1
attr_reader :hash
-
-
1
def current_hash
-
239
@hash_stack.last
-
end
-
-
1
def start_document
-
17
@hash = {}
-
17
@hash_stack = [@hash]
-
end
-
-
1
def end_document
-
16
raise "Parse stack not empty!" if @hash_stack.size > 1
-
end
-
-
1
def error(error_message)
-
1
raise error_message
-
end
-
-
1
def start_element(name, attrs = [])
-
33
new_hash = { CONTENT_KEY => '' }.merge(Hash[attrs])
-
33
new_hash[HASH_SIZE_KEY] = new_hash.size + 1
-
-
33
case current_hash[name]
-
when Array then current_hash[name] << new_hash
-
2
when Hash then current_hash[name] = [current_hash[name], new_hash]
-
31
when nil then current_hash[name] = new_hash
-
end
-
-
33
@hash_stack.push(new_hash)
-
end
-
-
1
def end_element(name)
-
33
if current_hash.length > current_hash.delete(HASH_SIZE_KEY) && current_hash[CONTENT_KEY].blank? || current_hash[CONTENT_KEY] == ''
-
19
current_hash.delete(CONTENT_KEY)
-
end
-
33
@hash_stack.pop
-
end
-
-
1
def characters(string)
-
51
current_hash[CONTENT_KEY] << string
-
end
-
-
1
alias_method :cdata_block, :characters
-
end
-
-
1
attr_accessor :document_class
-
1
self.document_class = HashBuilder
-
-
1
def parse(data)
-
19
if !data.respond_to?(:read)
-
18
data = StringIO.new(data || '')
-
end
-
-
19
char = data.getc
-
19
if char.nil?
-
2
{}
-
else
-
17
data.ungetc(char)
-
17
document = self.document_class.new
-
17
parser = Nokogiri::XML::SAX::Parser.new(document)
-
17
parser.parse(data)
-
16
document.hash
-
end
-
end
-
end
-
end
-
1
require 'active_support/core_ext/kernel/reporting'
-
1
require 'active_support/core_ext/object/blank'
-
1
require 'stringio'
-
-
1
module ActiveSupport
-
1
module XmlMini_REXML #:nodoc:
-
1
extend self
-
-
1
CONTENT_KEY = '__content__'.freeze
-
-
# Parse an XML Document string or IO into a simple hash.
-
#
-
# Same as XmlSimple::xml_in but doesn't shoot itself in the foot,
-
# and uses the defaults from Active Support.
-
#
-
# data::
-
# XML Document string or IO to parse
-
1
def parse(data)
-
51
if !data.respond_to?(:read)
-
50
data = StringIO.new(data || '')
-
end
-
-
51
char = data.getc
-
51
if char.nil?
-
{}
-
else
-
51
data.ungetc(char)
-
52
silence_warnings { require 'rexml/document' } unless defined?(REXML::Document)
-
51
doc = REXML::Document.new(data)
-
-
51
if doc.root
-
51
merge_element!({}, doc.root)
-
else
-
raise REXML::ParseException,
-
"The document #{doc.to_s.inspect} does not have a valid root"
-
end
-
end
-
end
-
-
1
private
-
# Convert an XML element and merge into the hash
-
#
-
# hash::
-
# Hash to merge the converted element into.
-
# element::
-
# XML element to merge into hash
-
1
def merge_element!(hash, element)
-
180
merge!(hash, element.name, collapse(element))
-
end
-
-
# Actually converts an XML document element into a data structure.
-
#
-
# element::
-
# The document element to be collapsed.
-
1
def collapse(element)
-
180
hash = get_attributes(element)
-
-
180
if element.has_elements?
-
183
element.each_element {|child| merge_element!(hash, child) }
-
54
merge_texts!(hash, element) unless empty_content?(element)
-
54
hash
-
else
-
126
merge_texts!(hash, element)
-
end
-
end
-
-
# Merge all the texts of an element into the hash
-
#
-
# hash::
-
# Hash to add the converted element to.
-
# element::
-
# XML element whose texts are to me merged into the hash
-
1
def merge_texts!(hash, element)
-
129
unless element.has_text?
-
27
hash
-
else
-
# must use value to prevent double-escaping
-
101
texts = ''
-
219
element.texts.each { |t| texts << t.value }
-
101
merge!(hash, CONTENT_KEY, texts)
-
end
-
end
-
-
# Adds a new key/value pair to an existing Hash. If the key to be added
-
# already exists and the existing value associated with key is not
-
# an Array, it will be wrapped in an Array. Then the new value is
-
# appended to that Array.
-
#
-
# hash::
-
# Hash to add key/value pair to.
-
# key::
-
# Key to be added.
-
# value::
-
# Value to be associated with key.
-
1
def merge!(hash, key, value)
-
280
if hash.has_key?(key)
-
7
if hash[key].instance_of?(Array)
-
hash[key] << value
-
else
-
7
hash[key] = [hash[key], value]
-
end
-
elsif value.instance_of?(Array)
-
hash[key] = [value]
-
else
-
273
hash[key] = value
-
end
-
280
hash
-
end
-
-
# Converts the attributes array of an XML element into a hash.
-
# Returns an empty Hash if node has no attributes.
-
#
-
# element::
-
# XML element to extract attributes from.
-
1
def get_attributes(element)
-
180
attributes = {}
-
283
element.attributes.each { |n,v| attributes[n] = v }
-
180
attributes
-
end
-
-
# Determines if a document element has text content
-
#
-
# element::
-
# XML element to be checked.
-
1
def empty_content?(element)
-
54
element.texts.join.blank?
-
end
-
end
-
end
-
# bust gem prelude
-
1
require 'bundler'
-
1
Bundler.setup
-
#!/usr/bin/env ruby
-
-
#--
-
# Copyright 2004 by Jim Weirich (jim@weirichhouse.org).
-
# All rights reserved.
-
-
# Permission is granted for use, copying, modification, distribution,
-
# and distribution of modified versions of this work as long as the
-
# above copyright notice is included.
-
#++
-
-
1
require 'builder/xmlmarkup'
-
1
require 'builder/xmlevents'
-
#!/usr/bin/env ruby
-
#--
-
# Copyright 2004, 2006 by Jim Weirich (jim@weirichhouse.org).
-
# All rights reserved.
-
-
# Permission is granted for use, copying, modification, distribution,
-
# and distribution of modified versions of this work as long as the
-
# above copyright notice is included.
-
#++
-
-
######################################################################
-
# BlankSlate has been promoted to a top level name and is now
-
# available as a standalone gem. We make the name available in the
-
# Builder namespace for compatibility.
-
#
-
1
module Builder
-
1
if Object::const_defined?(:BasicObject)
-
1
BlankSlate = ::BasicObject
-
else
-
require 'blankslate'
-
BlankSlate = ::BlankSlate
-
end
-
end
-
#!/usr/bin/env ruby
-
-
# The XChar library is provided courtesy of Sam Ruby (See
-
# http://intertwingly.net/stories/2005/09/28/xchar.rb)
-
-
# --------------------------------------------------------------------
-
-
# If the Builder::XChar module is not currently defined, fail on any
-
# name clashes in standard library classes.
-
-
1
module Builder
-
1
def self.check_for_name_collision(klass, method_name, defined_constant=nil)
-
if klass.method_defined?(method_name.to_s)
-
fail RuntimeError,
-
"Name Collision: Method '#{method_name}' is already defined in #{klass}"
-
end
-
end
-
end
-
-
1
if ! defined?(Builder::XChar) and ! String.method_defined?(:encode)
-
Builder.check_for_name_collision(String, "to_xs")
-
Builder.check_for_name_collision(Fixnum, "xchr")
-
end
-
-
######################################################################
-
1
module Builder
-
-
####################################################################
-
# XML Character converter, from Sam Ruby:
-
# (see http://intertwingly.net/stories/2005/09/28/xchar.rb).
-
#
-
1
module XChar # :nodoc:
-
-
# See
-
# http://intertwingly.net/stories/2004/04/14/i18n.html#CleaningWindows
-
# for details.
-
1
CP1252 = { # :nodoc:
-
128 => 8364, # euro sign
-
130 => 8218, # single low-9 quotation mark
-
131 => 402, # latin small letter f with hook
-
132 => 8222, # double low-9 quotation mark
-
133 => 8230, # horizontal ellipsis
-
134 => 8224, # dagger
-
135 => 8225, # double dagger
-
136 => 710, # modifier letter circumflex accent
-
137 => 8240, # per mille sign
-
138 => 352, # latin capital letter s with caron
-
139 => 8249, # single left-pointing angle quotation mark
-
140 => 338, # latin capital ligature oe
-
142 => 381, # latin capital letter z with caron
-
145 => 8216, # left single quotation mark
-
146 => 8217, # right single quotation mark
-
147 => 8220, # left double quotation mark
-
148 => 8221, # right double quotation mark
-
149 => 8226, # bullet
-
150 => 8211, # en dash
-
151 => 8212, # em dash
-
152 => 732, # small tilde
-
153 => 8482, # trade mark sign
-
154 => 353, # latin small letter s with caron
-
155 => 8250, # single right-pointing angle quotation mark
-
156 => 339, # latin small ligature oe
-
158 => 382, # latin small letter z with caron
-
159 => 376, # latin capital letter y with diaeresis
-
}
-
-
# See http://www.w3.org/TR/REC-xml/#dt-chardata for details.
-
1
PREDEFINED = {
-
38 => '&', # ampersand
-
60 => '<', # left angle bracket
-
62 => '>', # right angle bracket
-
}
-
-
# See http://www.w3.org/TR/REC-xml/#charsets for details.
-
1
VALID = [
-
0x9, 0xA, 0xD,
-
(0x20..0xD7FF),
-
(0xE000..0xFFFD),
-
(0x10000..0x10FFFF)
-
]
-
-
# http://www.fileformat.info/info/unicode/char/fffd/index.htm
-
1
REPLACEMENT_CHAR =
-
if String.method_defined?(:encode)
-
1
"\uFFFD"
-
elsif $KCODE == 'UTF8'
-
"\xEF\xBF\xBD"
-
else
-
'*'
-
end
-
end
-
-
end
-
-
-
1
if String.method_defined?(:encode)
-
1
module Builder
-
1
module XChar # :nodoc:
-
1
CP1252_DIFFERENCES, UNICODE_EQUIVALENT = Builder::XChar::CP1252.each.
-
inject([[],[]]) {|(domain,range),(key,value)|
-
27
[domain << key,range << value]
-
2
}.map {|seq| seq.pack('U*').force_encoding('utf-8')}
-
-
1
XML_PREDEFINED = Regexp.new('[' +
-
Builder::XChar::PREDEFINED.keys.pack('U*').force_encoding('utf-8') +
-
']')
-
-
1
INVALID_XML_CHAR = Regexp.new('[^'+
-
Builder::XChar::VALID.map { |item|
-
6
case item
-
when Fixnum
-
3
[item].pack('U').force_encoding('utf-8')
-
when Range
-
3
[item.first, '-'.ord, item.last].pack('UUU').force_encoding('utf-8')
-
end
-
}.join +
-
']')
-
-
1
ENCODING_BINARY = Encoding.find('BINARY')
-
1
ENCODING_UTF8 = Encoding.find('UTF-8')
-
1
ENCODING_ISO1 = Encoding.find('ISO-8859-1')
-
-
# convert a string to valid UTF-8, compensating for a number of
-
# common errors.
-
1
def XChar.unicode(string)
-
125
if string.encoding == ENCODING_BINARY
-
if string.ascii_only?
-
string
-
else
-
string = string.clone.force_encoding(ENCODING_UTF8)
-
if string.valid_encoding?
-
string
-
else
-
string.encode(ENCODING_UTF8, ENCODING_ISO1)
-
end
-
end
-
-
125
elsif string.encoding == ENCODING_UTF8
-
if string.valid_encoding?
-
string
-
else
-
string.encode(ENCODING_UTF8, ENCODING_ISO1)
-
end
-
-
else
-
125
string.encode(ENCODING_UTF8)
-
end
-
end
-
-
# encode a string per XML rules
-
1
def XChar.encode(string)
-
125
unicode(string).
-
tr(CP1252_DIFFERENCES, UNICODE_EQUIVALENT).
-
gsub(INVALID_XML_CHAR, REPLACEMENT_CHAR).
-
4
gsub(XML_PREDEFINED) {|c| PREDEFINED[c.ord]}
-
end
-
end
-
end
-
-
else
-
-
######################################################################
-
# Enhance the Fixnum class with a XML escaped character conversion.
-
#
-
class Fixnum
-
XChar = Builder::XChar if ! defined?(XChar)
-
-
# XML escaped version of chr. When <tt>escape</tt> is set to false
-
# the CP1252 fix is still applied but utf-8 characters are not
-
# converted to character entities.
-
def xchr(escape=true)
-
n = XChar::CP1252[self] || self
-
case n when *XChar::VALID
-
XChar::PREDEFINED[n] or
-
(n<128 ? n.chr : (escape ? "&##{n};" : [n].pack('U*')))
-
else
-
Builder::XChar::REPLACEMENT_CHAR
-
end
-
end
-
end
-
-
-
######################################################################
-
# Enhance the String class with a XML escaped character version of
-
# to_s.
-
#
-
class String
-
# XML escaped version of to_s. When <tt>escape</tt> is set to false
-
# the CP1252 fix is still applied but utf-8 characters are not
-
# converted to character entities.
-
def to_xs(escape=true)
-
unpack('U*').map {|n| n.xchr(escape)}.join # ASCII, UTF-8
-
rescue
-
unpack('C*').map {|n| n.xchr}.join # ISO-8859-1, WIN-1252
-
end
-
end
-
end
-
#!/usr/bin/env ruby
-
-
1
require 'builder/blankslate'
-
-
1
module Builder
-
-
# Generic error for builder
-
1
class IllegalBlockError < RuntimeError; end
-
-
# XmlBase is a base class for building XML builders. See
-
# Builder::XmlMarkup and Builder::XmlEvents for examples.
-
1
class XmlBase < BlankSlate
-
-
1
class << self
-
1
attr_accessor :cache_method_calls
-
end
-
-
# Create an XML markup builder.
-
#
-
# out:: Object receiving the markup. +out+ must respond to
-
# <tt><<</tt>.
-
# indent:: Number of spaces used for indentation (0 implies no
-
# indentation and no line breaks).
-
# initial:: Level of initial indentation.
-
# encoding:: When <tt>encoding</tt> and $KCODE are set to 'utf-8'
-
# characters aren't converted to character entities in
-
# the output stream.
-
1
def initialize(indent=0, initial=0, encoding='utf-8')
-
33
@indent = indent
-
33
@level = initial
-
33
@encoding = encoding.downcase
-
end
-
-
# Create a tag named +sym+. Other than the first argument which
-
# is the tag name, the arguments are the same as the tags
-
# implemented via <tt>method_missing</tt>.
-
1
def tag!(sym, *args, &block)
-
138
text = nil
-
138
attrs = nil
-
138
sym = "#{sym}:#{args.shift}" if args.first.kind_of?(::Symbol)
-
138
sym = sym.to_sym unless sym.class == ::Symbol
-
138
args.each do |arg|
-
175
case arg
-
when ::Hash
-
91
attrs ||= {}
-
91
attrs.merge!(arg)
-
when nil
-
# do nothing
-
else
-
82
text ||= ''
-
82
text << arg.to_s
-
end
-
end
-
138
if block
-
51
unless text.nil?
-
::Kernel::raise ::ArgumentError,
-
"XmlMarkup cannot mix a text argument with a block"
-
end
-
51
_indent
-
51
_start_tag(sym, attrs)
-
51
_newline
-
51
begin
-
51
_nested_structures(block)
-
ensure
-
51
_indent
-
51
_end_tag(sym)
-
51
_newline
-
end
-
elsif text.nil?
-
5
_indent
-
5
_start_tag(sym, attrs, true)
-
5
_newline
-
else
-
82
_indent
-
82
_start_tag(sym, attrs)
-
82
text! text
-
82
_end_tag(sym)
-
82
_newline
-
end
-
138
@target
-
end
-
-
# Create XML markup based on the name of the method. This method
-
# is never invoked directly, but is called for each markup method
-
# in the markup block that isn't cached.
-
1
def method_missing(sym, *args, &block)
-
6
cache_method_call(sym) if ::Builder::XmlBase.cache_method_calls
-
6
tag!(sym, *args, &block)
-
end
-
-
# Append text to the output target. Escape any markup. May be
-
# used within the markup brackets as:
-
#
-
# builder.p { |b| b.br; b.text! "HI" } #=> <p><br/>HI</p>
-
1
def text!(text)
-
87
_text(_escape(text))
-
end
-
-
# Append text to the output target without escaping any markup.
-
# May be used within the markup brackets as:
-
#
-
# builder.p { |x| x << "<br/>HI" } #=> <p><br/>HI</p>
-
#
-
# This is useful when using non-builder enabled software that
-
# generates strings. Just insert the string directly into the
-
# builder without changing the inserted markup.
-
#
-
# It is also useful for stacking builder objects. Builders only
-
# use <tt><<</tt> to append to the target, so by supporting this
-
# method/operation builders can use other builders as their
-
# targets.
-
1
def <<(text)
-
_text(text)
-
end
-
-
# For some reason, nil? is sent to the XmlMarkup object. If nil?
-
# is not defined and method_missing is invoked, some strange kind
-
# of recursion happens. Since nil? won't ever be an XML tag, it
-
# is pretty safe to define it here. (Note: this is an example of
-
# cargo cult programming,
-
# cf. http://fishbowl.pastiche.org/2004/10/13/cargo_cult_programming).
-
1
def nil?
-
false
-
end
-
-
1
private
-
-
1
require 'builder/xchar'
-
1
if ::String.method_defined?(:encode)
-
1
def _escape(text)
-
125
result = XChar.encode(text)
-
125
begin
-
125
encoding = ::Encoding::find(@encoding)
-
125
raise Exception if encoding.dummy?
-
125
result.encode(encoding)
-
rescue
-
# if the encoding can't be supported, use numeric character references
-
result.
-
gsub(/[^\u0000-\u007F]/) {|c| "&##{c.ord};"}.
-
force_encoding('ascii')
-
end
-
end
-
else
-
def _escape(text)
-
if (text.method(:to_xs).arity == 0)
-
text.to_xs
-
else
-
text.to_xs((@encoding != 'utf-8' or $KCODE != 'UTF8'))
-
end
-
end
-
end
-
-
1
def _escape_attribute(text)
-
38
_escape(text).gsub("\n", " ").gsub("\r", " ").
-
gsub(%r{"}, '"') # " WART
-
end
-
-
1
def _newline
-
191
return if @indent == 0
-
5
text! "\n"
-
end
-
-
1
def _indent
-
191
return if @indent == 0 || @level == 0
-
text!(" " * (@level * @indent))
-
end
-
-
1
def _nested_structures(block)
-
51
@level += 1
-
51
block.call(self)
-
ensure
-
51
@level -= 1
-
end
-
-
# If XmlBase.cache_method_calls = true, we dynamicly create the method
-
# missed as an instance method on the XMLBase object. Because XML
-
# documents are usually very repetative in nature, the next node will
-
# be handled by the new method instead of method_missing. As
-
# method_missing is very slow, this speeds up document generation
-
# significantly.
-
1
def cache_method_call(sym)
-
12
class << self; self; end.class_eval do
-
6
define_method(sym) do |*args, &block|
-
tag!(sym, *args, &block)
-
end
-
end
-
end
-
end
-
-
1
XmlBase.cache_method_calls = true
-
-
end
-
#!/usr/bin/env ruby
-
-
#--
-
# Copyright 2004 by Jim Weirich (jim@weirichhouse.org).
-
# All rights reserved.
-
-
# Permission is granted for use, copying, modification, distribution,
-
# and distribution of modified versions of this work as long as the
-
# above copyright notice is included.
-
#++
-
-
1
require 'builder/xmlmarkup'
-
-
1
module Builder
-
-
# Create a series of SAX-like XML events (e.g. start_tag, end_tag)
-
# from the markup code. XmlEvent objects are used in a way similar
-
# to XmlMarkup objects, except that a series of events are generated
-
# and passed to a handler rather than generating character-based
-
# markup.
-
#
-
# Usage:
-
# xe = Builder::XmlEvents.new(hander)
-
# xe.title("HI") # Sends start_tag/end_tag/text messages to the handler.
-
#
-
# Indentation may also be selected by providing value for the
-
# indentation size and initial indentation level.
-
#
-
# xe = Builder::XmlEvents.new(handler, indent_size, initial_indent_level)
-
#
-
# == XML Event Handler
-
#
-
# The handler object must expect the following events.
-
#
-
# [<tt>start_tag(tag, attrs)</tt>]
-
# Announces that a new tag has been found. +tag+ is the name of
-
# the tag and +attrs+ is a hash of attributes for the tag.
-
#
-
# [<tt>end_tag(tag)</tt>]
-
# Announces that an end tag for +tag+ has been found.
-
#
-
# [<tt>text(text)</tt>]
-
# Announces that a string of characters (+text+) has been found.
-
# A series of characters may be broken up into more than one
-
# +text+ call, so the client cannot assume that a single
-
# callback contains all the text data.
-
#
-
1
class XmlEvents < XmlMarkup
-
1
def text!(text)
-
@target.text(text)
-
end
-
-
1
def _start_tag(sym, attrs, end_too=false)
-
@target.start_tag(sym, attrs)
-
_end_tag(sym) if end_too
-
end
-
-
1
def _end_tag(sym)
-
@target.end_tag(sym)
-
end
-
end
-
-
end
-
#!/usr/bin/env ruby
-
#--
-
# Copyright 2004, 2005 by Jim Weirich (jim@weirichhouse.org).
-
# All rights reserved.
-
-
# Permission is granted for use, copying, modification, distribution,
-
# and distribution of modified versions of this work as long as the
-
# above copyright notice is included.
-
#++
-
-
# Provide a flexible and easy to use Builder for creating XML markup.
-
# See XmlBuilder for usage details.
-
-
1
require 'builder/xmlbase'
-
-
1
module Builder
-
-
# Create XML markup easily. All (well, almost all) methods sent to
-
# an XmlMarkup object will be translated to the equivalent XML
-
# markup. Any method with a block will be treated as an XML markup
-
# tag with nested markup in the block.
-
#
-
# Examples will demonstrate this easier than words. In the
-
# following, +xm+ is an +XmlMarkup+ object.
-
#
-
# xm.em("emphasized") # => <em>emphasized</em>
-
# xm.em { xm.b("emp & bold") } # => <em><b>emph & bold</b></em>
-
# xm.a("A Link", "href"=>"http://onestepback.org")
-
# # => <a href="http://onestepback.org">A Link</a>
-
# xm.div { xm.br } # => <div><br/></div>
-
# xm.target("name"=>"compile", "option"=>"fast")
-
# # => <target option="fast" name="compile"\>
-
# # NOTE: order of attributes is not specified.
-
#
-
# xm.instruct! # <?xml version="1.0" encoding="UTF-8"?>
-
# xm.html { # <html>
-
# xm.head { # <head>
-
# xm.title("History") # <title>History</title>
-
# } # </head>
-
# xm.body { # <body>
-
# xm.comment! "HI" # <!-- HI -->
-
# xm.h1("Header") # <h1>Header</h1>
-
# xm.p("paragraph") # <p>paragraph</p>
-
# } # </body>
-
# } # </html>
-
#
-
# == Notes:
-
#
-
# * The order that attributes are inserted in markup tags is
-
# undefined.
-
#
-
# * Sometimes you wish to insert text without enclosing tags. Use
-
# the <tt>text!</tt> method to accomplish this.
-
#
-
# Example:
-
#
-
# xm.div { # <div>
-
# xm.text! "line"; xm.br # line<br/>
-
# xm.text! "another line"; xmbr # another line<br/>
-
# } # </div>
-
#
-
# * The special XML characters <, >, and & are converted to <,
-
# > and & automatically. Use the <tt><<</tt> operation to
-
# insert text without modification.
-
#
-
# * Sometimes tags use special characters not allowed in ruby
-
# identifiers. Use the <tt>tag!</tt> method to handle these
-
# cases.
-
#
-
# Example:
-
#
-
# xml.tag!("SOAP:Envelope") { ... }
-
#
-
# will produce ...
-
#
-
# <SOAP:Envelope> ... </SOAP:Envelope>"
-
#
-
# <tt>tag!</tt> will also take text and attribute arguments (after
-
# the tag name) like normal markup methods. (But see the next
-
# bullet item for a better way to handle XML namespaces).
-
#
-
# * Direct support for XML namespaces is now available. If the
-
# first argument to a tag call is a symbol, it will be joined to
-
# the tag to produce a namespace:tag combination. It is easier to
-
# show this than describe it.
-
#
-
# xml.SOAP :Envelope do ... end
-
#
-
# Just put a space before the colon in a namespace to produce the
-
# right form for builder (e.g. "<tt>SOAP:Envelope</tt>" =>
-
# "<tt>xml.SOAP :Envelope</tt>")
-
#
-
# * XmlMarkup builds the markup in any object (called a _target_)
-
# that accepts the <tt><<</tt> method. If no target is given,
-
# then XmlMarkup defaults to a string target.
-
#
-
# Examples:
-
#
-
# xm = Builder::XmlMarkup.new
-
# result = xm.title("yada")
-
# # result is a string containing the markup.
-
#
-
# buffer = ""
-
# xm = Builder::XmlMarkup.new(buffer)
-
# # The markup is appended to buffer (using <<)
-
#
-
# xm = Builder::XmlMarkup.new(STDOUT)
-
# # The markup is written to STDOUT (using <<)
-
#
-
# xm = Builder::XmlMarkup.new
-
# x2 = Builder::XmlMarkup.new(:target=>xm)
-
# # Markup written to +x2+ will be send to +xm+.
-
#
-
# * Indentation is enabled by providing the number of spaces to
-
# indent for each level as a second argument to XmlBuilder.new.
-
# Initial indentation may be specified using a third parameter.
-
#
-
# Example:
-
#
-
# xm = Builder.new(:indent=>2)
-
# # xm will produce nicely formatted and indented XML.
-
#
-
# xm = Builder.new(:indent=>2, :margin=>4)
-
# # xm will produce nicely formatted and indented XML with 2
-
# # spaces per indent and an over all indentation level of 4.
-
#
-
# builder = Builder::XmlMarkup.new(:target=>$stdout, :indent=>2)
-
# builder.name { |b| b.first("Jim"); b.last("Weirich) }
-
# # prints:
-
# # <name>
-
# # <first>Jim</first>
-
# # <last>Weirich</last>
-
# # </name>
-
#
-
# * The instance_eval implementation which forces self to refer to
-
# the message receiver as self is now obsolete. We now use normal
-
# block calls to execute the markup block. This means that all
-
# markup methods must now be explicitly send to the xml builder.
-
# For instance, instead of
-
#
-
# xml.div { strong("text") }
-
#
-
# you need to write:
-
#
-
# xml.div { xml.strong("text") }
-
#
-
# Although more verbose, the subtle change in semantics within the
-
# block was found to be prone to error. To make this change a
-
# little less cumbersome, the markup block now gets the markup
-
# object sent as an argument, allowing you to use a shorter alias
-
# within the block.
-
#
-
# For example:
-
#
-
# xml_builder = Builder::XmlMarkup.new
-
# xml_builder.div { |xml|
-
# xml.stong("text")
-
# }
-
#
-
1
class XmlMarkup < XmlBase
-
-
# Create an XML markup builder. Parameters are specified by an
-
# option hash.
-
#
-
# :target=><em>target_object</em>::
-
# Object receiving the markup. +target_object+ must respond to
-
# the <tt><<(<em>a_string</em>)</tt> operator and return
-
# itself. The default target is a plain string target.
-
#
-
# :indent=><em>indentation</em>::
-
# Number of spaces used for indentation. The default is no
-
# indentation and no line breaks.
-
#
-
# :margin=><em>initial_indentation_level</em>::
-
# Amount of initial indentation (specified in levels, not
-
# spaces).
-
#
-
# :escape_attrs=><em>OBSOLETE</em>::
-
# The :escape_attrs option is no longer supported by builder
-
# (and will be quietly ignored). String attribute values are
-
# now automatically escaped. If you need unescaped attribute
-
# values (perhaps you are using entities in the attribute
-
# values), then give the value as a Symbol. This allows much
-
# finer control over escaping attribute values.
-
#
-
1
def initialize(options={})
-
33
indent = options[:indent] || 0
-
33
margin = options[:margin] || 0
-
33
super(indent, margin)
-
33
@target = options[:target] || ""
-
end
-
-
# Return the target of the builder.
-
1
def target!
-
6
@target
-
end
-
-
1
def comment!(comment_text)
-
_ensure_no_block ::Kernel::block_given?
-
_special("<!-- ", " -->", comment_text, nil)
-
end
-
-
# Insert an XML declaration into the XML markup.
-
#
-
# For example:
-
#
-
# xml.declare! :ELEMENT, :blah, "yada"
-
# # => <!ELEMENT blah "yada">
-
1
def declare!(inst, *args, &block)
-
_indent
-
@target << "<!#{inst}"
-
args.each do |arg|
-
case arg
-
when ::String
-
@target << %{ "#{arg}"} # " WART
-
when ::Symbol
-
@target << " #{arg}"
-
end
-
end
-
if ::Kernel::block_given?
-
@target << " ["
-
_newline
-
_nested_structures(block)
-
@target << "]"
-
end
-
@target << ">"
-
_newline
-
end
-
-
# Insert a processing instruction into the XML markup. E.g.
-
#
-
# For example:
-
#
-
# xml.instruct!
-
# #=> <?xml version="1.0" encoding="UTF-8"?>
-
# xml.instruct! :aaa, :bbb=>"ccc"
-
# #=> <?aaa bbb="ccc"?>
-
#
-
# Note: If the encoding is setup to "UTF-8" and the value of
-
# $KCODE is "UTF8", then builder will emit UTF-8 encoded strings
-
# rather than the entity encoding normally used.
-
1
def instruct!(directive_tag=:xml, attrs={})
-
2
_ensure_no_block ::Kernel::block_given?
-
2
if directive_tag == :xml
-
2
a = { :version=>"1.0", :encoding=>"UTF-8" }
-
2
attrs = a.merge attrs
-
2
@encoding = attrs[:encoding].downcase
-
end
-
_special(
-
2
"<?#{directive_tag}",
-
"?>",
-
nil,
-
attrs,
-
[:version, :encoding, :standalone])
-
end
-
-
# Insert a CDATA section into the XML markup.
-
#
-
# For example:
-
#
-
# xml.cdata!("text to be included in cdata")
-
# #=> <![CDATA[text to be included in cdata]]>
-
#
-
1
def cdata!(text)
-
_ensure_no_block ::Kernel::block_given?
-
_special("<![CDATA[", "]]>", text.gsub(']]>', ']]]]><![CDATA[>'), nil)
-
end
-
-
1
private
-
-
# NOTE: All private methods of a builder object are prefixed when
-
# a "_" character to avoid possible conflict with XML tag names.
-
-
# Insert text directly in to the builder's target.
-
1
def _text(text)
-
87
@target << text
-
end
-
-
# Insert special instruction.
-
1
def _special(open, close, data=nil, attrs=nil, order=[])
-
2
_indent
-
2
@target << open
-
2
@target << data if data
-
2
_insert_attributes(attrs, order) if attrs
-
2
@target << close
-
2
_newline
-
end
-
-
# Start an XML tag. If <tt>end_too</tt> is true, then the start
-
# tag is also the end tag (e.g. <br/>
-
1
def _start_tag(sym, attrs, end_too=false)
-
138
@target << "<#{sym}"
-
138
_insert_attributes(attrs)
-
138
@target << "/" if end_too
-
138
@target << ">"
-
end
-
-
# Insert an ending tag.
-
1
def _end_tag(sym)
-
133
@target << "</#{sym}>"
-
end
-
-
# Insert the attributes (given in the hash).
-
1
def _insert_attributes(attrs, order=[])
-
140
return if attrs.nil?
-
93
order.each do |k|
-
6
v = attrs[k]
-
6
@target << %{ #{k}="#{_attr_value(v)}"} if v # " WART
-
end
-
93
attrs.each do |k, v|
-
38
@target << %{ #{k}="#{_attr_value(v)}"} unless order.member?(k) # " WART
-
end
-
end
-
-
1
def _attr_value(value)
-
38
case value
-
when ::Symbol
-
value.to_s
-
else
-
38
_escape_attribute(value.to_s)
-
end
-
end
-
-
1
def _ensure_no_block(got_block)
-
2
if got_block
-
::Kernel::raise IllegalBlockError.new(
-
"Blocks are not allowed on XML instructions"
-
)
-
end
-
end
-
-
end
-
-
end
-
1
require 'dalli/client'
-
1
require 'dalli/ring'
-
1
require 'dalli/server'
-
1
require 'dalli/socket'
-
1
require 'dalli/version'
-
1
require 'dalli/options'
-
1
require 'dalli/compressor'
-
1
require 'dalli/railtie' if defined?(::Rails::Railtie)
-
-
1
module Dalli
-
# generic error
-
1
class DalliError < RuntimeError; end
-
# socket/server communication error
-
1
class NetworkError < DalliError; end
-
# no server available/alive error
-
1
class RingError < DalliError; end
-
# application error in marshalling serialization
-
1
class MarshalError < DalliError; end
-
# application error in marshalling deserialization or decompression
-
1
class UnmarshalError < DalliError; end
-
-
1
def self.logger
-
159
@logger ||= (rails_logger || default_logger)
-
end
-
-
1
def self.rails_logger
-
1
(defined?(Rails) && Rails.respond_to?(:logger) && Rails.logger) ||
-
2
(defined?(RAILS_DEFAULT_LOGGER) && RAILS_DEFAULT_LOGGER.respond_to?(:debug) && RAILS_DEFAULT_LOGGER)
-
end
-
-
1
def self.default_logger
-
1
require 'logger'
-
1
l = Logger.new(STDOUT)
-
1
l.level = Logger::INFO
-
1
l
-
end
-
-
1
def self.logger=(logger)
-
@logger = logger
-
end
-
-
# Default serialization to Marshal
-
1
@serializer = Marshal
-
-
1
def self.serializer
-
90
@serializer
-
end
-
-
1
def self.serializer=(serializer)
-
@serializer = serializer
-
end
-
-
# Default serialization to Dalli::Compressor
-
1
@compressor = Compressor
-
-
1
def self.compressor
-
@compressor
-
end
-
-
1
def self.compressor=(compressor)
-
@compressor = compressor
-
end
-
end
-
-
1
if defined?(RAILS_VERSION) && RAILS_VERSION < '3'
-
raise Dalli::DalliError, "Dalli #{Dalli::VERSION} does not support Rails version < 3.0"
-
end
-
1
require 'digest/md5'
-
1
require 'set'
-
-
# encoding: ascii
-
1
module Dalli
-
1
class Client
-
-
##
-
# Dalli::Client is the main class which developers will use to interact with
-
# the memcached server. Usage:
-
#
-
# Dalli::Client.new(['localhost:11211:10', 'cache-2.example.com:11211:5', '192.168.0.1:22122:5'],
-
# :threadsafe => true, :failover => true, :expires_in => 300)
-
#
-
# servers is an Array of "host:port:weight" where weight allows you to distribute cache unevenly.
-
# Both weight and port are optional. If you pass in nil, Dalli will use the <tt>MEMCACHE_SERVERS</tt>
-
# environment variable or default to 'localhost:11211' if it is not present.
-
#
-
# Options:
-
# - :namespace - prepend each key with this value to provide simple namespacing.
-
# - :failover - if a server is down, look for and store values on another server in the ring. Default: true.
-
# - :threadsafe - ensure that only one thread is actively using a socket at a time. Default: true.
-
# - :expires_in - default TTL in seconds if you do not pass TTL as a parameter to an individual operation, defaults to 0 or forever
-
# - :compress - defaults to false, if true Dalli will compress values larger than 1024 bytes before
-
# sending them to memcached.
-
#
-
1
def initialize(servers=nil, options={})
-
304
@servers = servers || env_servers || '127.0.0.1:11211'
-
304
@options = normalize_options(options)
-
304
@ring = nil
-
304
@servers_in_use = nil
-
end
-
-
#
-
# The standard memcached instruction set
-
#
-
-
##
-
# Turn on quiet aka noreply support.
-
# All relevant operations within this block will be effectively
-
# pipelined as Dalli will use 'quiet' operations where possible.
-
# Currently supports the set, add, replace and delete operations.
-
1
def multi
-
old, Thread.current[:dalli_multi] = Thread.current[:dalli_multi], true
-
yield
-
ensure
-
Thread.current[:dalli_multi] = old
-
end
-
-
1
def get(key, options=nil)
-
358
resp = perform(:get, key)
-
358
resp.nil? || resp == 'Not found' ? nil : resp
-
end
-
-
##
-
# Fetch multiple keys efficiently.
-
# Returns a hash of { 'key' => 'value', 'key2' => 'value1' }
-
1
def get_multi(*keys)
-
3
return {} if keys.empty?
-
3
options = nil
-
3
options = keys.pop if keys.last.is_a?(Hash) || keys.last.nil?
-
3
ring.lock do
-
3
self.servers_in_use = Set.new
-
-
3
keys.flatten.each do |key|
-
5
begin
-
5
perform(:getkq, key)
-
rescue DalliError, NetworkError => e
-
Dalli.logger.debug { e.inspect }
-
Dalli.logger.debug { "unable to get key #{key}" }
-
end
-
end
-
-
3
values = {}
-
3
servers_in_use.each do |server|
-
3
next unless server.alive?
-
3
begin
-
3
server.request(:noop).each_pair do |key, value|
-
5
values[key_without_namespace(key)] = value
-
end
-
rescue DalliError, NetworkError => e
-
Dalli.logger.debug { e.inspect }
-
Dalli.logger.debug { "results from this server will be missing" }
-
end
-
end
-
3
values
-
end
-
ensure
-
3
self.servers_in_use = nil
-
end
-
-
1
def fetch(key, ttl=nil, options=nil)
-
ttl ||= @options[:expires_in].to_i
-
val = get(key, options)
-
if val.nil? && block_given?
-
val = yield
-
add(key, val, ttl, options)
-
end
-
val
-
end
-
-
##
-
# compare and swap values using optimistic locking.
-
# Fetch the existing value for key.
-
# If it exists, yield the value to the block.
-
# Add the block's return value as the new value for the key.
-
# Add will fail if someone else changed the value.
-
#
-
# Returns:
-
# - nil if the key did not exist.
-
# - false if the value was changed by someone else.
-
# - true if the value was successfully updated.
-
1
def cas(key, ttl=nil, options=nil, &block)
-
ttl ||= @options[:expires_in].to_i
-
(value, cas) = perform(:cas, key)
-
value = (!value || value == 'Not found') ? nil : value
-
if value
-
newvalue = block.call(value)
-
perform(:set, key, newvalue, ttl, cas, options)
-
end
-
end
-
-
1
def set(key, value, ttl=nil, options=nil)
-
261
ttl ||= @options[:expires_in].to_i
-
261
perform(:set, key, value, ttl, 0, options)
-
end
-
-
##
-
# Conditionally add a key/value pair, if the key does not already exist
-
# on the server. Returns true if the operation succeeded.
-
1
def add(key, value, ttl=nil, options=nil)
-
ttl ||= @options[:expires_in].to_i
-
perform(:add, key, value, ttl, options)
-
end
-
-
##
-
# Conditionally add a key/value pair, only if the key already exists
-
# on the server. Returns true if the operation succeeded.
-
1
def replace(key, value, ttl=nil, options=nil)
-
ttl ||= @options[:expires_in].to_i
-
perform(:replace, key, value, ttl, options)
-
end
-
-
1
def delete(key)
-
109
perform(:delete, key)
-
end
-
-
##
-
# Append value to the value already stored on the server for 'key'.
-
# Appending only works for values stored with :raw => true.
-
1
def append(key, value)
-
perform(:append, key, value.to_s)
-
end
-
-
##
-
# Prepend value to the value already stored on the server for 'key'.
-
# Prepending only works for values stored with :raw => true.
-
1
def prepend(key, value)
-
perform(:prepend, key, value.to_s)
-
end
-
-
1
def flush(delay=0)
-
154
time = -delay
-
308
ring.servers.map { |s| s.request(:flush, time += delay) }
-
end
-
-
1
alias_method :flush_all, :flush
-
-
##
-
# Incr adds the given amount to the counter on the memcached server.
-
# Amt must be a positive integer value.
-
#
-
# If default is nil, the counter must already exist or the operation
-
# will fail and will return nil. Otherwise this method will return
-
# the new value for the counter.
-
#
-
# Note that the ttl will only apply if the counter does not already
-
# exist. To increase an existing counter and update its TTL, use
-
# #cas.
-
1
def incr(key, amt=1, ttl=nil, default=nil)
-
105
raise ArgumentError, "Positive values only: #{amt}" if amt < 0
-
105
ttl ||= @options[:expires_in].to_i
-
105
perform(:incr, key, amt.to_i, ttl, default)
-
end
-
-
##
-
# Decr subtracts the given amount from the counter on the memcached server.
-
# Amt must be a positive integer value.
-
#
-
# memcached counters are unsigned and cannot hold negative values. Calling
-
# decr on a counter which is 0 will just return 0.
-
#
-
# If default is nil, the counter must already exist or the operation
-
# will fail and will return nil. Otherwise this method will return
-
# the new value for the counter.
-
#
-
# Note that the ttl will only apply if the counter does not already
-
# exist. To decrease an existing counter and update its TTL, use
-
# #cas.
-
1
def decr(key, amt=1, ttl=nil, default=nil)
-
105
raise ArgumentError, "Positive values only: #{amt}" if amt < 0
-
105
ttl ||= @options[:expires_in].to_i
-
105
perform(:decr, key, amt.to_i, ttl, default)
-
end
-
-
##
-
# Touch updates expiration time for a given key.
-
#
-
# Returns true if key exists, otherwise nil.
-
1
def touch(key, ttl=nil)
-
ttl ||= @options[:expires_in].to_i
-
resp = perform(:touch, key, ttl)
-
resp.nil? ? nil : true
-
end
-
-
##
-
# Collect the stats for each server.
-
# Returns a hash like { 'hostname:port' => { 'stat1' => 'value1', ... }, 'hostname2:port' => { ... } }
-
1
def stats
-
1
values = {}
-
1
ring.servers.each do |server|
-
1
values["#{server.hostname}:#{server.port}"] = server.alive? ? server.request(:stats) : nil
-
end
-
1
values
-
end
-
-
##
-
# Reset stats for each server.
-
1
def reset_stats
-
ring.servers.map do |server|
-
server.alive? ? server.request(:reset_stats) : nil
-
end
-
end
-
-
##
-
# Close our connection to each server.
-
# If you perform another operation after this, the connections will be re-established.
-
1
def close
-
if @ring
-
@ring.servers.each { |s| s.close }
-
@ring = nil
-
end
-
end
-
1
alias_method :reset, :close
-
-
1
private
-
-
1
def ring
-
@ring ||= Dalli::Ring.new(
-
Array(@servers).map do |s|
-
159
server_options = {}
-
159
if s =~ %r{\Amemcached://}
-
uri = URI.parse(s)
-
server_options[:username] = uri.user
-
server_options[:password] = uri.password
-
s = "#{uri.host}:#{uri.port}"
-
end
-
159
Dalli::Server.new(s, @options.merge(server_options))
-
end, @options
-
1101
)
-
end
-
-
1
def env_servers
-
1
ENV['MEMCACHE_SERVERS'] ? ENV['MEMCACHE_SERVERS'].split(',') : nil
-
end
-
-
# Chokepoint method for instrumentation
-
1
def perform(op, key, *args)
-
943
key = key.to_s
-
943
key = validate_key(key)
-
943
begin
-
943
server = ring.server_for_key(key)
-
943
ret = server.request(op, key, *args)
-
943
servers_in_use << server if servers_in_use
-
943
ret
-
rescue NetworkError => e
-
Dalli.logger.debug { e.inspect }
-
Dalli.logger.debug { "retrying request with new server" }
-
retry
-
end
-
end
-
-
1
def servers_in_use
-
951
Thread.current[:"#{object_id}-servers"]
-
end
-
-
1
def servers_in_use=(value)
-
6
Thread.current[:"#{object_id}-servers"] = value
-
end
-
-
1
def validate_key(key)
-
943
raise ArgumentError, "key cannot be blank" if !key || key.length == 0
-
943
key = key_with_namespace(key)
-
943
if key.length > 250
-
namespace_length = @options[:namespace] ? @options[:namespace].size : 0
-
max_length_before_namespace = 212 - namespace_length
-
key = "#{key[0, max_length_before_namespace]}:md5:#{Digest::MD5.hexdigest(key)}"
-
end
-
943
return key
-
end
-
-
1
def key_with_namespace(key)
-
943
@options[:namespace] ? "#{@options[:namespace]}:#{key}" : key
-
end
-
-
1
def key_without_namespace(key)
-
5
@options[:namespace] ? key.sub(%r(\A#{@options[:namespace]}:), '') : key
-
end
-
-
1
def normalize_options(opts)
-
304
if opts[:compression]
-
Dalli.logger.warn "DEPRECATED: Dalli's :compression option is now just :compress => true. Please update your configuration."
-
opts[:compress] = opts.delete(:compression)
-
end
-
304
begin
-
304
opts[:expires_in] = opts[:expires_in].to_i if opts[:expires_in]
-
rescue NoMethodError
-
raise ArgumentError, "cannot convert :expires_in => #{opts[:expires_in].inspect} to an integer"
-
end
-
304
opts
-
end
-
end
-
end
-
1
require 'zlib'
-
-
1
module Dalli
-
1
class Compressor
-
1
def self.compress(data)
-
Zlib::Deflate.deflate(data)
-
end
-
-
1
def self.decompress(data)
-
Zlib::Inflate.inflate(data)
-
end
-
end
-
end
-
1
require 'thread'
-
1
require 'monitor'
-
-
1
module Dalli
-
-
# Make Dalli threadsafe by using a lock around all
-
# public server methods.
-
#
-
# Dalli::Server.extend(Dalli::Threadsafe)
-
#
-
1
module Threadsafe
-
1
def self.extended(obj)
-
159
obj.init_threadsafe
-
end
-
-
1
def request(op, *args)
-
1101
@lock.synchronize do
-
1101
super
-
end
-
end
-
-
1
def alive?
-
2048
@lock.synchronize do
-
2048
super
-
end
-
end
-
-
1
def close
-
@lock.synchronize do
-
super
-
end
-
end
-
-
1
def lock!
-
3
@lock.mon_enter
-
end
-
-
1
def unlock!
-
3
@lock.mon_exit
-
end
-
-
1
def init_threadsafe
-
159
@lock = Monitor.new
-
end
-
end
-
end
-
1
require 'digest/sha1'
-
1
require 'zlib'
-
-
1
module Dalli
-
1
class Ring
-
1
POINTS_PER_SERVER = 160 # this is the default in libmemcached
-
-
1
attr_accessor :servers, :continuum
-
-
1
def initialize(servers, options)
-
159
@servers = servers
-
159
@continuum = nil
-
159
if servers.size > 1
-
total_weight = servers.inject(0) { |memo, srv| memo + srv.weight }
-
continuum = []
-
servers.each do |server|
-
entry_count_for(server, servers.size, total_weight).times do |idx|
-
hash = Digest::SHA1.hexdigest("#{server.hostname}:#{server.port}:#{idx}")
-
value = Integer("0x#{hash[0..7]}")
-
continuum << Dalli::Ring::Entry.new(value, server)
-
end
-
end
-
@continuum = continuum.sort { |a, b| a.value <=> b.value }
-
end
-
-
159
threadsafe! unless options[:threadsafe] == false
-
159
@failover = options[:failover] != false
-
end
-
-
1
def server_for_key(key)
-
943
if @continuum
-
hkey = hash_for(key)
-
20.times do |try|
-
entryidx = self.class.binary_search(@continuum, hkey)
-
server = @continuum[entryidx].server
-
return server if server.alive?
-
break unless @failover
-
hkey = hash_for("#{try}#{key}")
-
end
-
else
-
943
server = @servers.first
-
943
return server if server && server.alive?
-
end
-
-
raise Dalli::RingError, "No server available"
-
end
-
-
1
def lock
-
6
@servers.each { |s| s.lock! }
-
3
begin
-
3
return yield
-
ensure
-
6
@servers.each { |s| s.unlock! }
-
end
-
end
-
-
1
private
-
-
1
def threadsafe!
-
159
@servers.each do |s|
-
159
s.extend(Dalli::Threadsafe)
-
end
-
end
-
-
1
def hash_for(key)
-
Zlib.crc32(key)
-
end
-
-
1
def entry_count_for(server, total_servers, total_weight)
-
((total_servers * POINTS_PER_SERVER * server.weight) / Float(total_weight)).floor
-
end
-
-
# Find the closest index in the Ring with value <= the given value
-
1
def self.binary_search(ary, value)
-
upper = ary.size - 1
-
lower = 0
-
idx = 0
-
-
while (lower <= upper) do
-
idx = (lower + upper) / 2
-
comp = ary[idx].value <=> value
-
-
if comp == 0
-
return idx
-
elsif comp > 0
-
upper = idx - 1
-
else
-
lower = idx + 1
-
end
-
end
-
return upper
-
end
-
-
1
class Entry
-
1
attr_reader :value
-
1
attr_reader :server
-
-
1
def initialize(val, srv)
-
@value = val
-
@server = srv
-
end
-
end
-
-
end
-
end
-
1
require 'socket'
-
1
require 'timeout'
-
-
1
module Dalli
-
1
class Server
-
1
attr_accessor :hostname
-
1
attr_accessor :port
-
1
attr_accessor :weight
-
1
attr_accessor :options
-
-
1
DEFAULTS = {
-
# seconds between trying to contact a remote server
-
:down_retry_delay => 1,
-
# connect/read/write timeout for socket operations
-
:socket_timeout => 0.5,
-
# times a socket operation may fail before considering the server dead
-
:socket_max_failures => 2,
-
# amount of time to sleep between retries when a failure occurs
-
:socket_failure_delay => 0.01,
-
# max size of value in bytes (default is 1 MB, can be overriden with "memcached -I <size>")
-
:value_max_bytes => 1024 * 1024,
-
# min byte size to attempt compression
-
:compression_min_size => 1024,
-
# max byte size for compression
-
:compression_max_size => false,
-
:username => nil,
-
:password => nil,
-
:keepalive => true
-
}
-
-
1
def initialize(attribs, options = {})
-
159
(@hostname, @port, @weight) = attribs.split(':')
-
159
@port ||= 11211
-
159
@port = Integer(@port)
-
159
@weight ||= 1
-
159
@weight = Integer(@weight)
-
159
@fail_count = 0
-
159
@down_at = nil
-
159
@last_down_at = nil
-
159
@options = DEFAULTS.merge(options)
-
159
@sock = nil
-
159
@msg = nil
-
159
@pid = nil
-
159
@inprogress = nil
-
end
-
-
# Chokepoint method for instrumentation
-
1
def request(op, *args)
-
1101
verify_state
-
1101
raise Dalli::NetworkError, "#{hostname}:#{port} is down: #{@error} #{@msg}" unless alive?
-
1101
begin
-
1101
send(op, *args)
-
rescue Dalli::NetworkError
-
raise
-
rescue Dalli::MarshalError => ex
-
Dalli.logger.error "Marshalling error for key '#{args.first}': #{ex.message}"
-
Dalli.logger.error "You are trying to cache a Ruby object which cannot be serialized to memcached."
-
Dalli.logger.error ex.backtrace.join("\n\t")
-
false
-
rescue Dalli::DalliError
-
raise
-
rescue => ex
-
Dalli.logger.error "Unexpected exception in Dalli: #{ex.class.name}: #{ex.message}"
-
Dalli.logger.error "This is a bug in Dalli, please enter an issue in Github if it does not already exist."
-
Dalli.logger.error ex.backtrace.join("\n\t")
-
down!
-
end
-
end
-
-
1
def alive?
-
2048
return true if @sock
-
-
159
if @last_down_at && @last_down_at + options[:down_retry_delay] >= Time.now
-
time = @last_down_at + options[:down_retry_delay] - Time.now
-
Dalli.logger.debug { "down_retry_delay not reached for #{hostname}:#{port} (%.3f seconds left)" % time }
-
return false
-
end
-
-
159
connect
-
159
!!@sock
-
rescue Dalli::NetworkError
-
false
-
end
-
-
1
def close
-
return unless @sock
-
@sock.close rescue nil
-
@sock = nil
-
@pid = nil
-
@inprogress = false
-
end
-
-
1
def lock!
-
end
-
-
1
def unlock!
-
end
-
-
# NOTE: Additional public methods should be overridden in Dalli::Threadsafe
-
-
1
private
-
-
1
def verify_state
-
1101
failure! if @inprogress
-
1101
failure! if @pid && @pid != Process.pid
-
end
-
-
1
def failure!
-
Dalli.logger.info { "#{hostname}:#{port} failed (count: #{@fail_count})" }
-
-
@fail_count += 1
-
if @fail_count >= options[:socket_max_failures]
-
down!
-
else
-
close
-
sleep(options[:socket_failure_delay]) if options[:socket_failure_delay]
-
raise Dalli::NetworkError, "Socket operation failed, retrying..."
-
end
-
end
-
-
1
def down!
-
close
-
-
@last_down_at = Time.now
-
-
if @down_at
-
time = Time.now - @down_at
-
Dalli.logger.debug { "#{hostname}:#{port} is still down (for %.3f seconds now)" % time }
-
else
-
@down_at = @last_down_at
-
Dalli.logger.warn { "#{hostname}:#{port} is down" }
-
end
-
-
@error = $! && $!.class.name
-
@msg = @msg || ($! && $!.message && !$!.message.empty? && $!.message)
-
raise Dalli::NetworkError, "#{hostname}:#{port} is down: #{@error} #{@msg}"
-
end
-
-
1
def up!
-
159
if @down_at
-
time = Time.now - @down_at
-
Dalli.logger.warn { "#{hostname}:#{port} is back (downtime was %.3f seconds)" % time }
-
end
-
-
159
@fail_count = 0
-
159
@down_at = nil
-
159
@last_down_at = nil
-
159
@msg = nil
-
159
@error = nil
-
end
-
-
1
def multi?
-
740
Thread.current[:dalli_multi]
-
end
-
-
1
def get(key)
-
358
req = [REQUEST, OPCODES[:get], key.bytesize, 0, 0, 0, key.bytesize, 0, 0, key].pack(FORMAT[:get])
-
358
write(req)
-
358
generic_response(true)
-
end
-
-
1
def getkq(key)
-
5
req = [REQUEST, OPCODES[:getkq], key.bytesize, 0, 0, 0, key.bytesize, 0, 0, key].pack(FORMAT[:getkq])
-
5
write(req)
-
end
-
-
1
def set(key, value, ttl, cas, options)
-
261
(value, flags) = serialize(key, value, options)
-
-
261
if under_max_value_size?(value)
-
261
req = [REQUEST, OPCODES[multi? ? :setq : :set], key.bytesize, 8, 0, 0, value.bytesize + key.bytesize + 8, 0, cas, flags, ttl, key, value].pack(FORMAT[:set])
-
261
write(req)
-
261
generic_response unless multi?
-
else
-
false
-
end
-
end
-
-
1
def add(key, value, ttl, options)
-
(value, flags) = serialize(key, value, options)
-
-
if under_max_value_size?(value)
-
req = [REQUEST, OPCODES[multi? ? :addq : :add], key.bytesize, 8, 0, 0, value.bytesize + key.bytesize + 8, 0, 0, flags, ttl, key, value].pack(FORMAT[:add])
-
write(req)
-
generic_response unless multi?
-
else
-
false
-
end
-
end
-
-
1
def replace(key, value, ttl, options)
-
(value, flags) = serialize(key, value, options)
-
-
if under_max_value_size?(value)
-
req = [REQUEST, OPCODES[multi? ? :replaceq : :replace], key.bytesize, 8, 0, 0, value.bytesize + key.bytesize + 8, 0, 0, flags, ttl, key, value].pack(FORMAT[:replace])
-
write(req)
-
generic_response unless multi?
-
else
-
false
-
end
-
end
-
-
1
def delete(key)
-
109
req = [REQUEST, OPCODES[multi? ? :deleteq : :delete], key.bytesize, 0, 0, 0, key.bytesize, 0, 0, key].pack(FORMAT[:delete])
-
109
write(req)
-
109
generic_response unless multi?
-
end
-
-
1
def flush(ttl)
-
154
req = [REQUEST, OPCODES[:flush], 0, 4, 0, 0, 4, 0, 0, 0].pack(FORMAT[:flush])
-
154
write(req)
-
154
generic_response
-
end
-
-
1
def decr(key, count, ttl, default)
-
105
expiry = default ? ttl : 0xFFFFFFFF
-
105
default ||= 0
-
105
(h, l) = split(count)
-
105
(dh, dl) = split(default)
-
105
req = [REQUEST, OPCODES[:decr], key.bytesize, 20, 0, 0, key.bytesize + 20, 0, 0, h, l, dh, dl, expiry, key].pack(FORMAT[:decr])
-
105
write(req)
-
105
body = generic_response
-
105
body ? longlong(*body.unpack('NN')) : body
-
end
-
-
1
def incr(key, count, ttl, default)
-
105
expiry = default ? ttl : 0xFFFFFFFF
-
105
default ||= 0
-
105
(h, l) = split(count)
-
105
(dh, dl) = split(default)
-
105
req = [REQUEST, OPCODES[:incr], key.bytesize, 20, 0, 0, key.bytesize + 20, 0, 0, h, l, dh, dl, expiry, key].pack(FORMAT[:incr])
-
105
write(req)
-
105
body = generic_response
-
105
body ? longlong(*body.unpack('NN')) : body
-
end
-
-
# Noop is a keepalive operation but also used to demarcate the end of a set of pipelined commands.
-
# We need to read all the responses at once.
-
1
def noop
-
3
req = [REQUEST, OPCODES[:noop], 0, 0, 0, 0, 0, 0, 0].pack(FORMAT[:noop])
-
3
write(req)
-
3
multi_response
-
end
-
-
1
def append(key, value)
-
req = [REQUEST, OPCODES[:append], key.bytesize, 0, 0, 0, value.bytesize + key.bytesize, 0, 0, key, value].pack(FORMAT[:append])
-
write(req)
-
generic_response
-
end
-
-
1
def prepend(key, value)
-
req = [REQUEST, OPCODES[:prepend], key.bytesize, 0, 0, 0, value.bytesize + key.bytesize, 0, 0, key, value].pack(FORMAT[:prepend])
-
write(req)
-
generic_response
-
end
-
-
1
def stats(info='')
-
1
req = [REQUEST, OPCODES[:stat], info.bytesize, 0, 0, 0, info.bytesize, 0, 0, info].pack(FORMAT[:stat])
-
1
write(req)
-
1
keyvalue_response
-
end
-
-
1
def reset_stats
-
req = [REQUEST, OPCODES[:stat], 'reset'.bytesize, 0, 0, 0, 'reset'.bytesize, 0, 0, 'reset'].pack(FORMAT[:stat])
-
write(req)
-
generic_response
-
end
-
-
1
def cas(key)
-
req = [REQUEST, OPCODES[:get], key.bytesize, 0, 0, 0, key.bytesize, 0, 0, key].pack(FORMAT[:get])
-
write(req)
-
cas_response
-
end
-
-
1
def version
-
159
req = [REQUEST, OPCODES[:version], 0, 0, 0, 0, 0, 0, 0].pack(FORMAT[:noop])
-
159
write(req)
-
159
generic_response
-
end
-
-
1
def touch(key, ttl)
-
req = [REQUEST, OPCODES[:touch], key.bytesize, 4, 0, 0, key.bytesize + 4, 0, 0, ttl, key].pack(FORMAT[:touch])
-
write(req)
-
generic_response
-
end
-
-
# http://www.hjp.at/zettel/m/memcached_flags.rxml
-
# Looks like most clients use bit 0 to indicate native language serialization
-
# and bit 1 to indicate gzip compression.
-
1
FLAG_SERIALIZED = 0x1
-
1
FLAG_COMPRESSED = 0x2
-
-
1
def serialize(key, value, options=nil)
-
261
marshalled = false
-
261
value = unless options && options[:raw]
-
48
marshalled = true
-
48
begin
-
48
Dalli.serializer.dump(value)
-
rescue => ex
-
# Marshalling can throw several different types of generic Ruby exceptions.
-
# Convert to a specific exception so we can special case it higher up the stack.
-
exc = Dalli::MarshalError.new(ex.message)
-
exc.set_backtrace ex.backtrace
-
raise exc
-
end
-
else
-
213
value.to_s
-
end
-
261
compressed = false
-
261
if @options[:compress] && value.bytesize >= @options[:compression_min_size] &&
-
(!@options[:compression_max_size] || value.bytesize <= @options[:compression_max_size])
-
value = Dalli.compressor.compress(value)
-
compressed = true
-
end
-
-
261
flags = 0
-
261
flags |= FLAG_COMPRESSED if compressed
-
261
flags |= FLAG_SERIALIZED if marshalled
-
261
[value, flags]
-
end
-
-
1
def deserialize(value, flags)
-
252
value = Dalli.compressor.decompress(value) if (flags & FLAG_COMPRESSED) != 0
-
252
value = Dalli.serializer.load(value) if (flags & FLAG_SERIALIZED) != 0
-
252
value
-
rescue TypeError
-
raise if $!.message !~ /needs to have method `_load'|exception class\/object expected|instance of IO needed|incompatible marshal file format/
-
raise UnmarshalError, "Unable to unmarshal value: #{$!.message}"
-
rescue ArgumentError
-
raise if $!.message !~ /undefined class|marshal data too short/
-
raise UnmarshalError, "Unable to unmarshal value: #{$!.message}"
-
rescue Zlib::Error
-
raise UnmarshalError, "Unable to uncompress value: #{$!.message}"
-
end
-
-
1
def cas_response
-
header = read(24)
-
raise Dalli::NetworkError, 'No response' if !header
-
(extras, _, status, count, _, cas) = header.unpack(CAS_HEADER)
-
data = read(count) if count > 0
-
if status == 1
-
nil
-
elsif status != 0
-
raise Dalli::DalliError, "Response error #{status}: #{RESPONSE_CODES[status]}"
-
elsif data
-
flags = data[0...extras].unpack('N')[0]
-
value = data[extras..-1]
-
data = deserialize(value, flags)
-
end
-
[data, cas]
-
end
-
-
1
CAS_HEADER = '@4CCnNNQ'
-
1
NORMAL_HEADER = '@4CCnN'
-
1
KV_HEADER = '@2n@6nN'
-
-
1
def under_max_value_size?(value)
-
261
value.bytesize <= @options[:value_max_bytes]
-
end
-
-
1
def generic_response(unpack=false)
-
1251
header = read(24)
-
1251
raise Dalli::NetworkError, 'No response' if !header
-
1251
(extras, _, status, count) = header.unpack(NORMAL_HEADER)
-
1251
data = read(count) if count > 0
-
1251
if status == 1
-
nil
-
1138
elsif status == 2 || status == 5
-
false # Not stored, normal status for add operation
-
1138
elsif status != 0
-
raise Dalli::DalliError, "Response error #{status}: #{RESPONSE_CODES[status]}"
-
1138
elsif data
-
614
flags = data[0...extras].unpack('N')[0]
-
614
value = data[extras..-1]
-
614
unpack ? deserialize(value, flags) : value
-
else
-
524
true
-
end
-
end
-
-
1
def keyvalue_response
-
1
hash = {}
-
1
loop do
-
49
header = read(24)
-
49
raise Dalli::NetworkError, 'No response' if !header
-
49
(key_length, _, body_length) = header.unpack(KV_HEADER)
-
49
return hash if key_length == 0
-
48
key = read(key_length)
-
48
value = read(body_length - key_length) if body_length - key_length > 0
-
48
hash[key] = value
-
end
-
end
-
-
1
def multi_response
-
3
hash = {}
-
3
loop do
-
8
header = read(24)
-
8
raise Dalli::NetworkError, 'No response' if !header
-
8
(key_length, _, body_length) = header.unpack(KV_HEADER)
-
8
return hash if key_length == 0
-
5
flags = read(4).unpack('N')[0]
-
5
key = read(key_length)
-
5
value = read(body_length - key_length - 4) if body_length - key_length - 4 > 0
-
5
hash[key] = deserialize(value, flags)
-
end
-
end
-
-
1
def write(bytes)
-
1260
begin
-
1260
@inprogress = true
-
1260
result = @sock.write(bytes)
-
1260
@inprogress = false
-
1260
result
-
rescue SystemCallError, Timeout::Error
-
failure!
-
end
-
end
-
-
1
def read(count)
-
2146
begin
-
2146
@inprogress = true
-
2146
data = @sock.readfull(count)
-
2146
@inprogress = false
-
2146
data
-
rescue SystemCallError, Timeout::Error, EOFError
-
failure!
-
end
-
end
-
-
1
def connect
-
159
Dalli.logger.debug { "Dalli::Server#connect #{hostname}:#{port}" }
-
-
159
begin
-
159
@pid = Process.pid
-
159
@sock = KSocket.open(hostname, port, options)
-
159
@version = version # trigger actual connect
-
159
sasl_authentication if need_auth?
-
159
up!
-
rescue Dalli::DalliError # SASL auth failure
-
raise
-
rescue SystemCallError, Timeout::Error, EOFError, SocketError
-
# SocketError = DNS resolution failure
-
failure!
-
end
-
end
-
-
1
def split(n)
-
420
[n >> 32, 0xFFFFFFFF & n]
-
end
-
-
1
def longlong(a, b)
-
208
(a << 32) | b
-
end
-
-
1
REQUEST = 0x80
-
1
RESPONSE = 0x81
-
-
1
RESPONSE_CODES = {
-
0 => 'No error',
-
1 => 'Key not found',
-
2 => 'Key exists',
-
3 => 'Value too large',
-
4 => 'Invalid arguments',
-
5 => 'Item not stored',
-
6 => 'Incr/decr on a non-numeric value',
-
0x20 => 'Authentication required',
-
0x81 => 'Unknown command',
-
0x82 => 'Out of memory',
-
}
-
-
1
OPCODES = {
-
:get => 0x00,
-
:set => 0x01,
-
:add => 0x02,
-
:replace => 0x03,
-
:delete => 0x04,
-
:incr => 0x05,
-
:decr => 0x06,
-
:flush => 0x08,
-
:noop => 0x0A,
-
:version => 0x0B,
-
:getkq => 0x0D,
-
:append => 0x0E,
-
:prepend => 0x0F,
-
:stat => 0x10,
-
:setq => 0x11,
-
:addq => 0x12,
-
:replaceq => 0x13,
-
:deleteq => 0x14,
-
:incrq => 0x15,
-
:decrq => 0x16,
-
:auth_negotiation => 0x20,
-
:auth_request => 0x21,
-
:auth_continue => 0x22,
-
:touch => 0x1C,
-
}
-
-
1
HEADER = "CCnCCnNNQ"
-
1
OP_FORMAT = {
-
:get => 'a*',
-
:set => 'NNa*a*',
-
:add => 'NNa*a*',
-
:replace => 'NNa*a*',
-
:delete => 'a*',
-
:incr => 'NNNNNa*',
-
:decr => 'NNNNNa*',
-
:flush => 'N',
-
:noop => '',
-
:getkq => 'a*',
-
:version => '',
-
:stat => 'a*',
-
:append => 'a*a*',
-
:prepend => 'a*a*',
-
:auth_request => 'a*a*',
-
:auth_continue => 'a*a*',
-
:touch => 'Na*',
-
}
-
18
FORMAT = OP_FORMAT.inject({}) { |memo, (k, v)| memo[k] = HEADER + v; memo }
-
-
-
#######
-
# SASL authentication support for NorthScale
-
#######
-
-
1
def need_auth?
-
159
@options[:username] || ENV['MEMCACHE_USERNAME']
-
end
-
-
1
def username
-
@options[:username] || ENV['MEMCACHE_USERNAME']
-
end
-
-
1
def password
-
@options[:password] || ENV['MEMCACHE_PASSWORD']
-
end
-
-
1
def sasl_authentication
-
Dalli.logger.info { "Dalli/SASL authenticating as #{username}" }
-
-
# negotiate
-
req = [REQUEST, OPCODES[:auth_negotiation], 0, 0, 0, 0, 0, 0, 0].pack(FORMAT[:noop])
-
write(req)
-
header = read(24)
-
raise Dalli::NetworkError, 'No response' if !header
-
(extras, type, status, count) = header.unpack(NORMAL_HEADER)
-
raise Dalli::NetworkError, "Unexpected message format: #{extras} #{count}" unless extras == 0 && count > 0
-
content = read(count)
-
return (Dalli.logger.debug("Authentication not required/supported by server")) if status == 0x81
-
mechanisms = content.split(' ')
-
raise NotImplementedError, "Dalli only supports the PLAIN authentication mechanism" if !mechanisms.include?('PLAIN')
-
-
# request
-
mechanism = 'PLAIN'
-
msg = "\x0#{username}\x0#{password}"
-
req = [REQUEST, OPCODES[:auth_request], mechanism.bytesize, 0, 0, 0, mechanism.bytesize + msg.bytesize, 0, 0, mechanism, msg].pack(FORMAT[:auth_request])
-
write(req)
-
-
header = read(24)
-
raise Dalli::NetworkError, 'No response' if !header
-
(extras, type, status, count) = header.unpack(NORMAL_HEADER)
-
raise Dalli::NetworkError, "Unexpected message format: #{extras} #{count}" unless extras == 0 && count > 0
-
content = read(count)
-
return Dalli.logger.info("Dalli/SASL: #{content}") if status == 0
-
-
raise Dalli::DalliError, "Error authenticating: #{status}" unless status == 0x21
-
raise NotImplementedError, "No two-step authentication mechanisms supported"
-
# (step, msg) = sasl.receive('challenge', content)
-
# raise Dalli::NetworkError, "Authentication failed" if sasl.failed? || step != 'response'
-
end
-
end
-
end
-
1
begin
-
1
require 'kgio'
-
puts "Using kgio socket IO" if defined?($TESTING) && $TESTING
-
-
class Dalli::Server::KSocket < Kgio::Socket
-
attr_accessor :options
-
-
def kgio_wait_readable
-
IO.select([self], nil, nil, options[:socket_timeout]) || raise(Timeout::Error, "IO timeout")
-
end
-
-
def kgio_wait_writable
-
IO.select(nil, [self], nil, options[:socket_timeout]) || raise(Timeout::Error, "IO timeout")
-
end
-
-
def self.open(host, port, options = {})
-
addr = Socket.pack_sockaddr_in(port, host)
-
sock = start(addr)
-
sock.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, true)
-
sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true) if options[:keepalive]
-
sock.options = options
-
sock.kgio_wait_writable
-
sock
-
end
-
-
alias :write :kgio_write
-
-
def readfull(count)
-
value = ''
-
loop do
-
value << kgio_read!(count - value.bytesize)
-
break if value.bytesize == count
-
end
-
value
-
end
-
-
end
-
-
if ::Kgio.respond_to?(:wait_readable=)
-
::Kgio.wait_readable = :kgio_wait_readable
-
::Kgio.wait_writable = :kgio_wait_writable
-
end
-
-
rescue LoadError
-
-
1
puts "Using standard socket IO (#{RUBY_DESCRIPTION})" if defined?($TESTING) && $TESTING
-
1
class Dalli::Server::KSocket < TCPSocket
-
1
attr_accessor :options
-
-
1
def self.open(host, port, options = {})
-
159
Timeout.timeout(options[:socket_timeout]) do
-
159
sock = new(host, port)
-
159
sock.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, true)
-
159
sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true) if options[:keepalive]
-
159
sock.options = { :host => host, :port => port }.merge(options)
-
159
sock
-
end
-
end
-
-
1
def readfull(count)
-
2146
value = ''
-
2146
begin
-
2146
loop do
-
2146
value << read_nonblock(count - value.bytesize)
-
2146
break if value.bytesize == count
-
end
-
rescue Errno::EAGAIN, Errno::EWOULDBLOCK
-
if IO.select([self], nil, nil, options[:socket_timeout])
-
retry
-
else
-
raise Timeout::Error, "IO timeout: #{options.inspect}"
-
end
-
end
-
2146
value
-
end
-
-
end
-
end
-
1
module Dalli
-
1
VERSION = '2.5.0'
-
end
-
1
require 'i18n/version'
-
1
require 'i18n/exceptions'
-
1
require 'i18n/interpolate/ruby'
-
-
1
module I18n
-
1
autoload :Backend, 'i18n/backend'
-
1
autoload :Config, 'i18n/config'
-
1
autoload :Gettext, 'i18n/gettext'
-
1
autoload :Locale, 'i18n/locale'
-
1
autoload :Tests, 'i18n/tests'
-
-
1
RESERVED_KEYS = [:scope, :default, :separator, :resolve, :object, :fallback, :format, :cascade, :throw, :raise, :rescue_format]
-
1
RESERVED_KEYS_PATTERN = /%\{(#{RESERVED_KEYS.join("|")})\}/
-
-
extend Module.new {
-
# Gets I18n configuration object.
-
1
def config
-
11482
Thread.current[:i18n_config] ||= I18n::Config.new
-
end
-
-
# Sets I18n configuration object.
-
1
def config=(value)
-
Thread.current[:i18n_config] = value
-
end
-
-
# Write methods which delegates to the configuration object
-
1
%w(locale backend default_locale available_locales default_separator
-
exception_handler load_path).each do |method|
-
7
module_eval <<-DELEGATORS, __FILE__, __LINE__ + 1
-
def #{method}
-
config.#{method}
-
end
-
-
def #{method}=(value)
-
config.#{method} = (value)
-
end
-
DELEGATORS
-
end
-
-
# Tells the backend to reload translations. Used in situations like the
-
# Rails development environment. Backends can implement whatever strategy
-
# is useful.
-
1
def reload!
-
config.backend.reload!
-
end
-
-
# Translates, pluralizes and interpolates a given key using a given locale,
-
# scope, and default, as well as interpolation values.
-
#
-
# *LOOKUP*
-
#
-
# Translation data is organized as a nested hash using the upper-level keys
-
# as namespaces. <em>E.g.</em>, ActionView ships with the translation:
-
# <tt>:date => {:formats => {:short => "%b %d"}}</tt>.
-
#
-
# Translations can be looked up at any level of this hash using the key argument
-
# and the scope option. <em>E.g.</em>, in this example <tt>I18n.t :date</tt>
-
# returns the whole translations hash <tt>{:formats => {:short => "%b %d"}}</tt>.
-
#
-
# Key can be either a single key or a dot-separated key (both Strings and Symbols
-
# work). <em>E.g.</em>, the short format can be looked up using both:
-
# I18n.t 'date.formats.short'
-
# I18n.t :'date.formats.short'
-
#
-
# Scope can be either a single key, a dot-separated key or an array of keys
-
# or dot-separated keys. Keys and scopes can be combined freely. So these
-
# examples will all look up the same short date format:
-
# I18n.t 'date.formats.short'
-
# I18n.t 'formats.short', :scope => 'date'
-
# I18n.t 'short', :scope => 'date.formats'
-
# I18n.t 'short', :scope => %w(date formats)
-
#
-
# *INTERPOLATION*
-
#
-
# Translations can contain interpolation variables which will be replaced by
-
# values passed to #translate as part of the options hash, with the keys matching
-
# the interpolation variable names.
-
#
-
# <em>E.g.</em>, with a translation <tt>:foo => "foo %{bar}"</tt> the option
-
# value for the key +bar+ will be interpolated into the translation:
-
# I18n.t :foo, :bar => 'baz' # => 'foo baz'
-
#
-
# *PLURALIZATION*
-
#
-
# Translation data can contain pluralized translations. Pluralized translations
-
# are arrays of singluar/plural versions of translations like <tt>['Foo', 'Foos']</tt>.
-
#
-
# Note that <tt>I18n::Backend::Simple</tt> only supports an algorithm for English
-
# pluralization rules. Other algorithms can be supported by custom backends.
-
#
-
# This returns the singular version of a pluralized translation:
-
# I18n.t :foo, :count => 1 # => 'Foo'
-
#
-
# These both return the plural version of a pluralized translation:
-
# I18n.t :foo, :count => 0 # => 'Foos'
-
# I18n.t :foo, :count => 2 # => 'Foos'
-
#
-
# The <tt>:count</tt> option can be used both for pluralization and interpolation.
-
# <em>E.g.</em>, with the translation
-
# <tt>:foo => ['%{count} foo', '%{count} foos']</tt>, count will
-
# be interpolated to the pluralized translation:
-
# I18n.t :foo, :count => 1 # => '1 foo'
-
#
-
# *DEFAULTS*
-
#
-
# This returns the translation for <tt>:foo</tt> or <tt>default</tt> if no translation was found:
-
# I18n.t :foo, :default => 'default'
-
#
-
# This returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt> if no
-
# translation for <tt>:foo</tt> was found:
-
# I18n.t :foo, :default => :bar
-
#
-
# Returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt>
-
# or <tt>default</tt> if no translations for <tt>:foo</tt> and <tt>:bar</tt> were found.
-
# I18n.t :foo, :default => [:bar, 'default']
-
#
-
# *BULK LOOKUP*
-
#
-
# This returns an array with the translations for <tt>:foo</tt> and <tt>:bar</tt>.
-
# I18n.t [:foo, :bar]
-
#
-
# Can be used with dot-separated nested keys:
-
# I18n.t [:'baz.foo', :'baz.bar']
-
#
-
# Which is the same as using a scope option:
-
# I18n.t [:foo, :bar], :scope => :baz
-
#
-
# *LAMBDAS*
-
#
-
# Both translations and defaults can be given as Ruby lambdas. Lambdas will be
-
# called and passed the key and options.
-
#
-
# E.g. assuming the key <tt>:salutation</tt> resolves to:
-
# lambda { |key, options| options[:gender] == 'm' ? "Mr. %{options[:name]}" : "Mrs. %{options[:name]}" }
-
#
-
# Then <tt>I18n.t(:salutation, :gender => 'w', :name => 'Smith') will result in "Mrs. Smith".
-
#
-
# It is recommended to use/implement lambdas in an "idempotent" way. E.g. when
-
# a cache layer is put in front of I18n.translate it will generate a cache key
-
# from the argument values passed to #translate. Therefor your lambdas should
-
# always return the same translations/values per unique combination of argument
-
# values.
-
1
def translate(*args)
-
3633
options = args.last.is_a?(Hash) ? args.pop : {}
-
3633
key = args.shift
-
3633
backend = config.backend
-
3633
locale = options.delete(:locale) || config.locale
-
3633
handling = options.delete(:throw) && :throw || options.delete(:raise) && :raise # TODO deprecate :raise
-
-
3633
raise I18n::ArgumentError if key.is_a?(String) && key.empty?
-
-
3633
result = catch(:exception) do
-
3633
if key.is_a?(Array)
-
key.map { |k| backend.translate(locale, k, options) }
-
else
-
3633
backend.translate(locale, key, options)
-
end
-
end
-
3633
result.is_a?(MissingTranslation) ? handle_exception(handling, result, locale, key, options) : result
-
end
-
1
alias :t :translate
-
-
# Wrapper for <tt>translate</tt> that adds <tt>:raise => true</tt>. With
-
# this option, if no translation is found, it will raise <tt>I18n::MissingTranslationData</tt>
-
1
def translate!(key, options={})
-
translate(key, options.merge(:raise => true))
-
end
-
1
alias :t! :translate!
-
-
# Transliterates UTF-8 characters to ASCII. By default this method will
-
# transliterate only Latin strings to an ASCII approximation:
-
#
-
# I18n.transliterate("Ærøskøbing")
-
# # => "AEroskobing"
-
#
-
# I18n.transliterate("日本語")
-
# # => "???"
-
#
-
# It's also possible to add support for per-locale transliterations. I18n
-
# expects transliteration rules to be stored at
-
# <tt>i18n.transliterate.rule</tt>.
-
#
-
# Transliteration rules can either be a Hash or a Proc. Procs must accept a
-
# single string argument. Hash rules inherit the default transliteration
-
# rules, while Procs do not.
-
#
-
# *Examples*
-
#
-
# Setting a Hash in <locale>.yml:
-
#
-
# i18n:
-
# transliterate:
-
# rule:
-
# ü: "ue"
-
# ö: "oe"
-
#
-
# Setting a Hash using Ruby:
-
#
-
# store_translations(:de, :i18n => {
-
# :transliterate => {
-
# :rule => {
-
# "ü" => "ue",
-
# "ö" => "oe"
-
# }
-
# }
-
# )
-
#
-
# Setting a Proc:
-
#
-
# translit = lambda {|string| MyTransliterator.transliterate(string) }
-
# store_translations(:xx, :i18n => {:transliterate => {:rule => translit})
-
#
-
# Transliterating strings:
-
#
-
# I18n.locale = :en
-
# I18n.transliterate("Jürgen") # => "Jurgen"
-
# I18n.locale = :de
-
# I18n.transliterate("Jürgen") # => "Juergen"
-
# I18n.transliterate("Jürgen", :locale => :en) # => "Jurgen"
-
# I18n.transliterate("Jürgen", :locale => :de) # => "Juergen"
-
1
def transliterate(*args)
-
375
options = args.pop if args.last.is_a?(Hash)
-
375
key = args.shift
-
375
locale = options && options.delete(:locale) || config.locale
-
375
handling = options && (options.delete(:throw) && :throw || options.delete(:raise) && :raise)
-
375
replacement = options && options.delete(:replacement)
-
375
config.backend.transliterate(locale, key, replacement)
-
rescue I18n::ArgumentError => exception
-
handle_exception(handling, exception, locale, key, options || {})
-
end
-
-
# Localizes certain objects, such as dates and numbers to local formatting.
-
1
def localize(object, options = {})
-
9
locale = options.delete(:locale) || config.locale
-
9
format = options.delete(:format) || :default
-
9
config.backend.localize(locale, object, format, options)
-
end
-
1
alias :l :localize
-
-
# Executes block with given I18n.locale set.
-
1
def with_locale(tmp_locale = nil)
-
if tmp_locale
-
current_locale = self.locale
-
self.locale = tmp_locale
-
end
-
yield
-
ensure
-
self.locale = current_locale if tmp_locale
-
end
-
-
# Merges the given locale, key and scope into a single array of keys.
-
# Splits keys that contain dots into multiple keys. Makes sure all
-
# keys are Symbols.
-
1
def normalize_keys(locale, key, scope, separator = nil)
-
3633
separator ||= I18n.default_separator
-
-
3633
keys = []
-
3633
keys.concat normalize_key(locale, separator)
-
3633
keys.concat normalize_key(scope, separator)
-
3633
keys.concat normalize_key(key, separator)
-
3633
keys
-
end
-
-
# making these private until Ruby 1.9.2 can send to protected methods again
-
# see http://redmine.ruby-lang.org/repositories/revision/ruby-19?rev=24280
-
1
private
-
-
# Any exceptions thrown in translate will be sent to the @@exception_handler
-
# which can be a Symbol, a Proc or any other Object unless they're forced to
-
# be raised or thrown (MissingTranslation).
-
#
-
# If exception_handler is a Symbol then it will simply be sent to I18n as
-
# a method call. A Proc will simply be called. In any other case the
-
# method #call will be called on the exception_handler object.
-
#
-
# Examples:
-
#
-
# I18n.exception_handler = :default_exception_handler # this is the default
-
# I18n.default_exception_handler(exception, locale, key, options) # will be called like this
-
#
-
# I18n.exception_handler = lambda { |*args| ... } # a lambda
-
# I18n.exception_handler.call(exception, locale, key, options) # will be called like this
-
#
-
# I18n.exception_handler = I18nExceptionHandler.new # an object
-
# I18n.exception_handler.call(exception, locale, key, options) # will be called like this
-
1
def handle_exception(handling, exception, locale, key, options)
-
case handling
-
when :raise
-
raise(exception.respond_to?(:to_exception) ? exception.to_exception : exception)
-
when :throw
-
throw :exception, exception
-
else
-
case handler = options[:exception_handler] || config.exception_handler
-
when Symbol
-
send(handler, exception, locale, key, options)
-
else
-
handler.call(exception, locale, key, options)
-
end
-
end
-
end
-
-
1
def normalize_key(key, separator)
-
10899
normalized_key_cache[separator][key] ||=
-
case key
-
when Array
-
key.map { |k| normalize_key(k, separator) }.flatten
-
else
-
48
keys = key.to_s.split(separator)
-
48
keys.delete('')
-
178
keys.map! { |k| k.to_sym }
-
48
keys
-
end
-
end
-
-
1
def normalized_key_cache
-
10900
@normalized_key_cache ||= Hash.new { |h,k| h[k] = {} }
-
end
-
-
# DEPRECATED. Use I18n.normalize_keys instead.
-
1
def normalize_translation_keys(locale, key, scope, separator = nil)
-
puts "I18n.normalize_translation_keys is deprecated. Please use the class I18n.normalize_keys instead."
-
normalize_keys(locale, key, scope, separator)
-
end
-
-
# DEPRECATED. Please use the I18n::ExceptionHandler class instead.
-
1
def default_exception_handler(exception, locale, key, options)
-
puts "I18n.default_exception_handler is deprecated. Please use the class I18n::ExceptionHandler instead " +
-
"(an instance of which is set to I18n.exception_handler by default)."
-
exception.is_a?(MissingTranslation) ? exception.message : raise(exception)
-
end
-
1
}
-
end
-
1
module I18n
-
1
module Backend
-
1
autoload :Base, 'i18n/backend/base'
-
1
autoload :InterpolationCompiler, 'i18n/backend/interpolation_compiler'
-
1
autoload :Cache, 'i18n/backend/cache'
-
1
autoload :Cascade, 'i18n/backend/cascade'
-
1
autoload :Chain, 'i18n/backend/chain'
-
1
autoload :Fallbacks, 'i18n/backend/fallbacks'
-
1
autoload :Flatten, 'i18n/backend/flatten'
-
1
autoload :Gettext, 'i18n/backend/gettext'
-
1
autoload :KeyValue, 'i18n/backend/key_value'
-
1
autoload :Memoize, 'i18n/backend/memoize'
-
1
autoload :Metadata, 'i18n/backend/metadata'
-
1
autoload :Pluralization, 'i18n/backend/pluralization'
-
1
autoload :Simple, 'i18n/backend/simple'
-
1
autoload :Transliterator, 'i18n/backend/transliterator'
-
end
-
end
-
1
require 'yaml'
-
1
require 'i18n/core_ext/hash'
-
1
require 'i18n/core_ext/kernel/surpress_warnings'
-
-
1
module I18n
-
1
module Backend
-
1
module Base
-
1
include I18n::Backend::Transliterator
-
-
# Accepts a list of paths to translation files. Loads translations from
-
# plain Ruby (*.rb) or YAML files (*.yml). See #load_rb and #load_yml
-
# for details.
-
1
def load_translations(*filenames)
-
1
filenames = I18n.load_path if filenames.empty?
-
4
filenames.flatten.each { |filename| load_file(filename) }
-
end
-
-
# This method receives a locale, a data hash and options for storing translations.
-
# Should be implemented
-
1
def store_translations(locale, data, options = {})
-
raise NotImplementedError
-
end
-
-
1
def translate(locale, key, options = {})
-
3633
raise InvalidLocale.new(locale) unless locale
-
3633
entry = key && lookup(locale, key, options[:scope], options)
-
-
3633
if options.empty?
-
13
entry = resolve(locale, key, entry, options)
-
else
-
3620
count, default = options.values_at(:count, :default)
-
3620
values = options.except(*RESERVED_KEYS)
-
3620
entry = entry.nil? && default ?
-
default(locale, key, default, options) : resolve(locale, key, entry, options)
-
end
-
-
3633
throw(:exception, I18n::MissingTranslation.new(locale, key, options)) if entry.nil?
-
3633
entry = entry.dup if entry.is_a?(String)
-
-
3633
entry = pluralize(locale, entry, count) if count
-
3633
entry = interpolate(locale, entry, values) if values
-
3633
entry
-
end
-
-
# Acts the same as +strftime+, but uses a localized version of the
-
# format string. Takes a key from the date/time formats translations as
-
# a format argument (<em>e.g.</em>, <tt>:short</tt> in <tt>:'date.formats'</tt>).
-
1
def localize(locale, object, format = :default, options = {})
-
9
raise ArgumentError, "Object must be a Date, DateTime or Time object. #{object.inspect} given." unless object.respond_to?(:strftime)
-
-
9
if Symbol === format
-
9
key = format
-
9
type = object.respond_to?(:sec) ? 'time' : 'date'
-
9
options = options.merge(:raise => true, :object => object, :locale => locale)
-
9
format = I18n.t(:"#{type}.formats.#{key}", options)
-
end
-
-
# format = resolve(locale, object, format, options)
-
9
format = format.to_s.gsub(/%[aAbBp]/) do |match|
-
10
case match
-
3
when '%a' then I18n.t(:"date.abbr_day_names", :locale => locale, :format => format)[object.wday]
-
when '%A' then I18n.t(:"date.day_names", :locale => locale, :format => format)[object.wday]
-
5
when '%b' then I18n.t(:"date.abbr_month_names", :locale => locale, :format => format)[object.mon]
-
2
when '%B' then I18n.t(:"date.month_names", :locale => locale, :format => format)[object.mon]
-
when '%p' then I18n.t(:"time.#{object.hour < 12 ? :am : :pm}", :locale => locale, :format => format) if object.respond_to? :hour
-
end
-
end
-
-
9
object.strftime(format)
-
end
-
-
# Returns an array of locales for which translations are available
-
# ignoring the reserved translation meta data key :i18n.
-
1
def available_locales
-
raise NotImplementedError
-
end
-
-
1
def reload!
-
@skip_syntax_deprecation = false
-
end
-
-
1
protected
-
-
# The method which actually looks up for the translation in the store.
-
1
def lookup(locale, key, scope = [], options = {})
-
raise NotImplementedError
-
end
-
-
# Evaluates defaults.
-
# If given subject is an Array, it walks the array and returns the
-
# first translation that can be resolved. Otherwise it tries to resolve
-
# the translation directly.
-
1
def default(locale, object, subject, options = {})
-
145
options = options.dup.reject { |key, value| key == :default }
-
65
case subject
-
when Array
-
subject.each do |item|
-
result = resolve(locale, object, item, options) and return result
-
end and nil
-
else
-
65
resolve(locale, object, subject, options)
-
end
-
end
-
-
# Resolves a translation.
-
# If the given subject is a Symbol, it will be translated with the
-
# given options. If it is a Proc then it will be evaluated. All other
-
# subjects will be returned directly.
-
1
def resolve(locale, object, subject, options = {})
-
3633
return subject if options[:resolve] == false
-
3631
result = catch(:exception) do
-
3631
case subject
-
when Symbol
-
I18n.translate(subject, options.merge(:locale => locale, :throw => true))
-
when Proc
-
date_or_time = options.delete(:object) || object
-
resolve(locale, object, subject.call(date_or_time, options))
-
else
-
3631
subject
-
end
-
end
-
3631
result unless result.is_a?(MissingTranslation)
-
end
-
-
# Picks a translation from an array according to English pluralization
-
# rules. It will pick the first translation if count is not equal to 1
-
# and the second translation if it is equal to 1. Other backends can
-
# implement more flexible or complex pluralization rules.
-
1
def pluralize(locale, entry, count)
-
298
return entry unless entry.is_a?(Hash) && count
-
-
65
key = :zero if count == 0 && entry.has_key?(:zero)
-
65
key ||= count == 1 ? :one : :other
-
65
raise InvalidPluralizationData.new(entry, count) unless entry.has_key?(key)
-
65
entry[key]
-
end
-
-
# Interpolates values into a given string.
-
#
-
# interpolate "file %{file} opened by %%{user}", :file => 'test.txt', :user => 'Mr. X'
-
# # => "file test.txt opened by %{user}"
-
1
def interpolate(locale, string, values = {})
-
3620
if string.is_a?(::String) && !values.empty?
-
298
I18n.interpolate(string, values)
-
else
-
3322
string
-
end
-
end
-
-
# Loads a single translations file by delegating to #load_rb or
-
# #load_yml depending on the file extension and directly merges the
-
# data to the existing translations. Raises I18n::UnknownFileType
-
# for all other file extensions.
-
1
def load_file(filename)
-
3
type = File.extname(filename).tr('.', '').downcase
-
3
raise UnknownFileType.new(type, filename) unless respond_to?(:"load_#{type}", true)
-
3
data = send(:"load_#{type}", filename)
-
3
raise InvalidLocaleData.new(filename) unless data.is_a?(Hash)
-
6
data.each { |locale, d| store_translations(locale, d || {}) }
-
end
-
-
# Loads a plain Ruby translations file. eval'ing the file must yield
-
# a Hash containing translation data with locales as toplevel keys.
-
1
def load_rb(filename)
-
eval(IO.read(filename), binding, filename)
-
end
-
-
# Loads a YAML translations file. The data must have locales as
-
# toplevel keys.
-
1
def load_yml(filename)
-
3
begin
-
3
YAML.load_file(filename)
-
rescue TypeError
-
nil
-
rescue SyntaxError
-
nil
-
end
-
end
-
end
-
end
-
end
-
1
module I18n
-
1
module Backend
-
# A simple backend that reads translations from YAML files and stores them in
-
# an in-memory hash. Relies on the Base backend.
-
#
-
# The implementation is provided by a Implementation module allowing to easily
-
# extend Simple backend's behavior by including modules. E.g.:
-
#
-
# module I18n::Backend::Pluralization
-
# def pluralize(*args)
-
# # extended pluralization logic
-
# super
-
# end
-
# end
-
#
-
# I18n::Backend::Simple.include(I18n::Backend::Pluralization)
-
1
class Simple
-
3
(class << self; self; end).class_eval { public :include }
-
-
1
module Implementation
-
1
include Base
-
-
1
def initialized?
-
3633
@initialized ||= false
-
end
-
-
# Stores translations for the given locale in memory.
-
# This uses a deep merge for the translations hash, so existing
-
# translations will be overwritten by new ones only at the deepest
-
# level of the hash.
-
1
def store_translations(locale, data, options = {})
-
32
locale = locale.to_sym
-
32
translations[locale] ||= {}
-
32
data = data.deep_symbolize_keys
-
32
translations[locale].deep_merge!(data)
-
end
-
-
# Get available locales from the translations hash
-
1
def available_locales
-
init_translations unless initialized?
-
translations.inject([]) do |locales, (locale, data)|
-
locales << locale unless (data.keys - [:i18n]).empty?
-
locales
-
end
-
end
-
-
# Clean up translations hash and set initialized to false on reload!
-
1
def reload!
-
@initialized = false
-
@translations = nil
-
super
-
end
-
-
1
protected
-
-
1
def init_translations
-
1
load_translations
-
1
@initialized = true
-
end
-
-
1
def translations
-
3697
@translations ||= {}
-
end
-
-
# Looks up a translation from the translations hash. Returns nil if
-
# eiher key is nil, or locale, scope or key do not exist as a key in the
-
# nested translations hash. Splits keys or scopes containing dots
-
# into multiple keys, i.e. <tt>currency.format</tt> is regarded the same as
-
# <tt>%w(currency format)</tt>.
-
1
def lookup(locale, key, scope = [], options = {})
-
3633
init_translations unless initialized?
-
3633
keys = I18n.normalize_keys(locale, key, scope, options[:separator])
-
-
3633
keys.inject(translations) do |result, _key|
-
13708
_key = _key.to_sym
-
13708
return nil unless result.is_a?(Hash) && result.has_key?(_key)
-
13643
result = result[_key]
-
13643
result = resolve(locale, _key, result, options.merge(:scope => nil)) if result.is_a?(Symbol)
-
13643
result
-
end
-
end
-
end
-
-
1
include Implementation
-
end
-
end
-
end
-
# encoding: utf-8
-
1
module I18n
-
1
module Backend
-
1
module Transliterator
-
1
DEFAULT_REPLACEMENT_CHAR = "?"
-
-
# Given a locale and a UTF-8 string, return the locale's ASCII
-
# approximation for the string.
-
1
def transliterate(locale, string, replacement = nil)
-
375
@transliterators ||= {}
-
375
@transliterators[locale] ||= Transliterator.get I18n.t(:'i18n.transliterate.rule',
-
:locale => locale, :resolve => false, :default => {})
-
375
@transliterators[locale].transliterate(string, replacement)
-
end
-
-
# Get a transliterator instance.
-
1
def self.get(rule = nil)
-
2
if !rule || rule.kind_of?(Hash)
-
2
HashTransliterator.new(rule)
-
elsif rule.kind_of? Proc
-
ProcTransliterator.new(rule)
-
else
-
raise I18n::ArgumentError, "Transliteration rule must be a proc or a hash."
-
end
-
end
-
-
# A transliterator which accepts a Proc as its transliteration rule.
-
1
class ProcTransliterator
-
1
def initialize(rule)
-
@rule = rule
-
end
-
-
1
def transliterate(string, replacement = nil)
-
@rule.call(string)
-
end
-
end
-
-
# A transliterator which accepts a Hash of characters as its translation
-
# rule.
-
1
class HashTransliterator
-
1
DEFAULT_APPROXIMATIONS = {
-
"À"=>"A", "Á"=>"A", "Â"=>"A", "Ã"=>"A", "Ä"=>"A", "Å"=>"A", "Æ"=>"AE",
-
"Ç"=>"C", "È"=>"E", "É"=>"E", "Ê"=>"E", "Ë"=>"E", "Ì"=>"I", "Í"=>"I",
-
"Î"=>"I", "Ï"=>"I", "Ð"=>"D", "Ñ"=>"N", "Ò"=>"O", "Ó"=>"O", "Ô"=>"O",
-
"Õ"=>"O", "Ö"=>"O", "×"=>"x", "Ø"=>"O", "Ù"=>"U", "Ú"=>"U", "Û"=>"U",
-
"Ü"=>"U", "Ý"=>"Y", "Þ"=>"Th", "ß"=>"ss", "à"=>"a", "á"=>"a", "â"=>"a",
-
"ã"=>"a", "ä"=>"a", "å"=>"a", "æ"=>"ae", "ç"=>"c", "è"=>"e", "é"=>"e",
-
"ê"=>"e", "ë"=>"e", "ì"=>"i", "í"=>"i", "î"=>"i", "ï"=>"i", "ð"=>"d",
-
"ñ"=>"n", "ò"=>"o", "ó"=>"o", "ô"=>"o", "õ"=>"o", "ö"=>"o", "ø"=>"o",
-
"ù"=>"u", "ú"=>"u", "û"=>"u", "ü"=>"u", "ý"=>"y", "þ"=>"th", "ÿ"=>"y",
-
"Ā"=>"A", "ā"=>"a", "Ă"=>"A", "ă"=>"a", "Ą"=>"A", "ą"=>"a", "Ć"=>"C",
-
"ć"=>"c", "Ĉ"=>"C", "ĉ"=>"c", "Ċ"=>"C", "ċ"=>"c", "Č"=>"C", "č"=>"c",
-
"Ď"=>"D", "ď"=>"d", "Đ"=>"D", "đ"=>"d", "Ē"=>"E", "ē"=>"e", "Ĕ"=>"E",
-
"ĕ"=>"e", "Ė"=>"E", "ė"=>"e", "Ę"=>"E", "ę"=>"e", "Ě"=>"E", "ě"=>"e",
-
"Ĝ"=>"G", "ĝ"=>"g", "Ğ"=>"G", "ğ"=>"g", "Ġ"=>"G", "ġ"=>"g", "Ģ"=>"G",
-
"ģ"=>"g", "Ĥ"=>"H", "ĥ"=>"h", "Ħ"=>"H", "ħ"=>"h", "Ĩ"=>"I", "ĩ"=>"i",
-
"Ī"=>"I", "ī"=>"i", "Ĭ"=>"I", "ĭ"=>"i", "Į"=>"I", "į"=>"i", "İ"=>"I",
-
"ı"=>"i", "IJ"=>"IJ", "ij"=>"ij", "Ĵ"=>"J", "ĵ"=>"j", "Ķ"=>"K", "ķ"=>"k",
-
"ĸ"=>"k", "Ĺ"=>"L", "ĺ"=>"l", "Ļ"=>"L", "ļ"=>"l", "Ľ"=>"L", "ľ"=>"l",
-
"Ŀ"=>"L", "ŀ"=>"l", "Ł"=>"L", "ł"=>"l", "Ń"=>"N", "ń"=>"n", "Ņ"=>"N",
-
"ņ"=>"n", "Ň"=>"N", "ň"=>"n", "ʼn"=>"'n", "Ŋ"=>"NG", "ŋ"=>"ng",
-
"Ō"=>"O", "ō"=>"o", "Ŏ"=>"O", "ŏ"=>"o", "Ő"=>"O", "ő"=>"o", "Œ"=>"OE",
-
"œ"=>"oe", "Ŕ"=>"R", "ŕ"=>"r", "Ŗ"=>"R", "ŗ"=>"r", "Ř"=>"R", "ř"=>"r",
-
"Ś"=>"S", "ś"=>"s", "Ŝ"=>"S", "ŝ"=>"s", "Ş"=>"S", "ş"=>"s", "Š"=>"S",
-
"š"=>"s", "Ţ"=>"T", "ţ"=>"t", "Ť"=>"T", "ť"=>"t", "Ŧ"=>"T", "ŧ"=>"t",
-
"Ũ"=>"U", "ũ"=>"u", "Ū"=>"U", "ū"=>"u", "Ŭ"=>"U", "ŭ"=>"u", "Ů"=>"U",
-
"ů"=>"u", "Ű"=>"U", "ű"=>"u", "Ų"=>"U", "ų"=>"u", "Ŵ"=>"W", "ŵ"=>"w",
-
"Ŷ"=>"Y", "ŷ"=>"y", "Ÿ"=>"Y", "Ź"=>"Z", "ź"=>"z", "Ż"=>"Z", "ż"=>"z",
-
"Ž"=>"Z", "ž"=>"z"
-
}
-
-
1
def initialize(rule = nil)
-
2
@rule = rule
-
2
add DEFAULT_APPROXIMATIONS
-
2
add rule if rule
-
end
-
-
1
def transliterate(string, replacement = nil)
-
375
string.gsub(/[^\x00-\x7f]/u) do |char|
-
35739
approximations[char] || replacement || DEFAULT_REPLACEMENT_CHAR
-
end
-
end
-
-
1
private
-
-
1
def approximations
-
35743
@approximations ||= {}
-
end
-
-
# Add transliteration rules to the approximations hash.
-
1
def add(hash)
-
385
hash.keys.each {|key| hash[key.to_s] = hash.delete(key).to_s}
-
4
approximations.merge! hash
-
end
-
end
-
end
-
end
-
end
-
1
module I18n
-
1
class Config
-
# The only configuration value that is not global and scoped to thread is :locale.
-
# It defaults to the default_locale.
-
1
def locale
-
3798
@locale ||= default_locale
-
end
-
-
# Sets the current locale pseudo-globally, i.e. in the Thread.current hash.
-
1
def locale=(locale)
-
1
@locale = locale.to_sym rescue nil
-
end
-
-
# Returns the current backend. Defaults to +Backend::Simple+.
-
1
def backend
-
4046
@@backend ||= Backend::Simple.new
-
end
-
-
# Sets the current backend. Used to set a custom backend.
-
1
def backend=(backend)
-
@@backend = backend
-
end
-
-
# Returns the current default locale. Defaults to :'en'
-
1
def default_locale
-
1
@@default_locale ||= :en
-
end
-
-
# Sets the current default locale. Used to set a custom default locale.
-
1
def default_locale=(locale)
-
@@default_locale = locale.to_sym rescue nil
-
end
-
-
# Returns an array of locales for which translations are available.
-
# Unless you explicitely set these through I18n.available_locales=
-
# the call will be delegated to the backend.
-
1
def available_locales
-
@@available_locales ||= nil
-
@@available_locales || backend.available_locales
-
end
-
-
# Sets the available locales.
-
1
def available_locales=(locales)
-
@@available_locales = Array(locales).map { |locale| locale.to_sym }
-
@@available_locales = nil if @@available_locales.empty?
-
end
-
-
# Returns the current default scope separator. Defaults to '.'
-
1
def default_separator
-
3633
@@default_separator ||= '.'
-
end
-
-
# Sets the current default scope separator.
-
1
def default_separator=(separator)
-
@@default_separator = separator
-
end
-
-
# Return the current exception handler. Defaults to :default_exception_handler.
-
1
def exception_handler
-
@@exception_handler ||= ExceptionHandler.new
-
end
-
-
# Sets the exception handler.
-
1
def exception_handler=(exception_handler)
-
@@exception_handler = exception_handler
-
end
-
-
# Allow clients to register paths providing translation data sources. The
-
# backend defines acceptable sources.
-
#
-
# E.g. the provided SimpleBackend accepts a list of paths to translation
-
# files which are either named *.rb and contain plain Ruby Hashes or are
-
# named *.yml and contain YAML data. So for the SimpleBackend clients may
-
# register translation files like this:
-
# I18n.load_path << 'path/to/locale/en.yml'
-
1
def load_path
-
4
@@load_path ||= []
-
end
-
-
# Sets the load path instance. Custom implementations are expected to
-
# behave like a Ruby Array.
-
1
def load_path=(load_path)
-
@@load_path = load_path
-
end
-
end
-
end
-
1
class Hash
-
def slice(*keep_keys)
-
h = {}
-
keep_keys.each { |key| h[key] = fetch(key) }
-
h
-
1
end unless Hash.method_defined?(:slice)
-
-
def except(*less_keys)
-
slice(*keys - less_keys)
-
1
end unless Hash.method_defined?(:except)
-
-
def deep_symbolize_keys
-
inject({}) { |result, (key, value)|
-
value = value.deep_symbolize_keys if value.is_a?(Hash)
-
result[(key.to_sym rescue key) || key] = value
-
result
-
}
-
1
end unless Hash.method_defined?(:deep_symbolize_keys)
-
-
# deep_merge_hash! by Stefan Rusterholz, see http://www.ruby-forum.com/topic/142809
-
1
MERGER = proc do |key, v1, v2|
-
Hash === v1 && Hash === v2 ? v1.merge(v2, &MERGER) : v2
-
end
-
-
def deep_merge!(data)
-
merge!(data, &MERGER)
-
1
end unless Hash.method_defined?(:deep_merge!)
-
end
-
-
1
module Kernel
-
1
def suppress_warnings
-
original_verbosity = $VERBOSE
-
$VERBOSE = nil
-
result = yield
-
$VERBOSE = original_verbosity
-
result
-
end
-
end
-
1
module I18n
-
# Handles exceptions raised in the backend. All exceptions except for
-
# MissingTranslationData exceptions are re-thrown. When a MissingTranslationData
-
# was caught the handler returns an error message string containing the key/scope.
-
# Note that the exception handler is not called when the option :throw was given.
-
1
class ExceptionHandler
-
include Module.new {
-
1
def call(exception, locale, key, options)
-
if exception.is_a?(MissingTranslation)
-
options[:rescue_format] == :html ? exception.html_message : exception.message
-
elsif exception.is_a?(Exception)
-
raise exception
-
else
-
throw :exception, exception
-
end
-
end
-
1
}
-
end
-
-
1
class ArgumentError < ::ArgumentError; end
-
-
1
class InvalidLocale < ArgumentError
-
1
attr_reader :locale
-
1
def initialize(locale)
-
@locale = locale
-
super "#{locale.inspect} is not a valid locale"
-
end
-
end
-
-
1
class InvalidLocaleData < ArgumentError
-
1
attr_reader :filename
-
1
def initialize(filename)
-
@filename = filename
-
super "can not load translations from #{filename}, expected it to return a hash, but does not"
-
end
-
end
-
-
1
class MissingTranslation
-
1
module Base
-
1
attr_reader :locale, :key, :options
-
-
1
def initialize(locale, key, options = nil)
-
@key, @locale, @options = key, locale, options.dup || {}
-
options.each { |k, v| self.options[k] = v.inspect if v.is_a?(Proc) }
-
end
-
-
1
def html_message
-
key = keys.last.to_s.gsub('_', ' ').gsub(/\b('?[a-z])/) { $1.capitalize }
-
%(<span class="translation_missing" title="translation missing: #{keys.join('.')}">#{key}</span>)
-
end
-
-
1
def keys
-
@keys ||= I18n.normalize_keys(locale, key, options[:scope]).tap do |keys|
-
keys << 'no key' if keys.size < 2
-
end
-
end
-
-
1
def message
-
"translation missing: #{keys.join('.')}"
-
end
-
1
alias :to_s :message
-
-
1
def to_exception
-
MissingTranslationData.new(locale, key, options)
-
end
-
end
-
-
1
include Base
-
end
-
-
1
class MissingTranslationData < ArgumentError
-
1
include MissingTranslation::Base
-
end
-
-
1
class InvalidPluralizationData < ArgumentError
-
1
attr_reader :entry, :count
-
1
def initialize(entry, count)
-
@entry, @count = entry, count
-
super "translation data #{entry.inspect} can not be used with :count => #{count}"
-
end
-
end
-
-
1
class MissingInterpolationArgument < ArgumentError
-
1
attr_reader :values, :string
-
1
def initialize(values, string)
-
@values, @string = values, string
-
super "missing interpolation argument in #{string.inspect} (#{values.inspect} given)"
-
end
-
end
-
-
1
class ReservedInterpolationKey < ArgumentError
-
1
attr_reader :key, :string
-
1
def initialize(key, string)
-
@key, @string = key, string
-
super "reserved key #{key.inspect} used in #{string.inspect}"
-
end
-
end
-
-
1
class UnknownFileType < ArgumentError
-
1
attr_reader :type, :filename
-
1
def initialize(type, filename)
-
@type, @filename = type, filename
-
super "can not load translations from #{filename}, the file type #{type} is not known"
-
end
-
end
-
end
-
# heavily based on Masao Mutoh's gettext String interpolation extension
-
# http://github.com/mutoh/gettext/blob/f6566738b981fe0952548c421042ad1e0cdfb31e/lib/gettext/core_ext/string.rb
-
-
1
module I18n
-
1
INTERPOLATION_PATTERN = Regexp.union(
-
/%%/,
-
/%\{(\w+)\}/, # matches placeholders like "%{foo}"
-
/%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps])/ # matches placeholders like "%<foo>.d"
-
)
-
-
1
class << self
-
1
def interpolate(string, values)
-
298
raise ReservedInterpolationKey.new($1.to_sym, string) if string =~ RESERVED_KEYS_PATTERN
-
298
raise ArgumentError.new('Interpolation values must be a Hash.') unless values.kind_of?(Hash)
-
298
interpolate_hash(string, values)
-
end
-
-
1
def interpolate_hash(string, values)
-
298
string.gsub(INTERPOLATION_PATTERN) do |match|
-
if match == '%%'
-
'%'
-
else
-
key = ($1 || $2).to_sym
-
value = values.key?(key) ? values[key] : raise(MissingInterpolationArgument.new(values, string))
-
value = value.call(values) if value.respond_to?(:call)
-
$3 ? sprintf("%#{$3}", value) : value
-
end
-
end
-
end
-
end
-
end
-
1
module I18n
-
1
VERSION = "0.6.1"
-
end
-
##
-
# = JavaScript Object Notation (JSON)
-
#
-
# JSON is a lightweight data-interchange format. It is easy for us
-
# humans to read and write. Plus, equally simple for machines to generate or parse.
-
# JSON is completely language agnostic, making it the ideal interchange format.
-
#
-
# Built on two universally available structures:
-
# 1. A collection of name/value pairs. Often referred to as an _object_, hash table, record, struct, keyed list, or associative array.
-
# 2. An ordered list of values. More commonly called an _array_, vector, sequence or list.
-
#
-
# To read more about JSON visit: http://json.org
-
#
-
# == Parsing JSON
-
#
-
# To parse a JSON string received by another application or generated within
-
# your existing application:
-
#
-
# require 'json'
-
#
-
# my_hash = JSON.parse('{"hello": "goodbye"}')
-
# puts my_hash["hello"] => "goodbye"
-
#
-
# Notice the extra quotes <tt>''</tt> around the hash notation. Ruby expects
-
# the argument to be a string and can't convert objects like a hash or array.
-
#
-
# Ruby converts your string into a hash
-
#
-
# == Generating JSON
-
#
-
# Creating a JSON string for communication or serialization is
-
# just as simple.
-
#
-
# require 'json'
-
#
-
# my_hash = {:hello => "goodbye"}
-
# puts JSON.generate(my_hash) => "{\"hello\":\"goodbye\"}"
-
#
-
# Or an alternative way:
-
#
-
# require 'json'
-
# puts {:hello => "goodbye"}.to_json => "{\"hello\":\"goodbye\"}"
-
#
-
# <tt>JSON.generate</tt> only allows objects or arrays to be converted
-
# to JSON syntax. <tt>to_json</tt>, however, accepts many Ruby classes
-
# even though it acts only as a method for serialization:
-
#
-
# require 'json'
-
#
-
# 1.to_json => "1"
-
#
-
-
1
require 'json/common'
-
1
module JSON
-
1
require 'json/version'
-
-
1
begin
-
1
require 'json/ext'
-
rescue LoadError
-
require 'json/pure'
-
end
-
end
-
1
require 'json/version'
-
1
require 'json/generic_object'
-
-
1
module JSON
-
1
class << self
-
# If _object_ is string-like, parse the string and return the parsed result
-
# as a Ruby data structure. Otherwise generate a JSON text from the Ruby
-
# data structure object and return it.
-
#
-
# The _opts_ argument is passed through to generate/parse respectively. See
-
# generate and parse for their documentation.
-
1
def [](object, opts = {})
-
if object.respond_to? :to_str
-
JSON.parse(object.to_str, opts)
-
else
-
JSON.generate(object, opts)
-
end
-
end
-
-
# Returns the JSON parser class that is used by JSON. This is either
-
# JSON::Ext::Parser or JSON::Pure::Parser.
-
1
attr_reader :parser
-
-
# Set the JSON parser class _parser_ to be used by JSON.
-
1
def parser=(parser) # :nodoc:
-
1
@parser = parser
-
1
remove_const :Parser if JSON.const_defined_in?(self, :Parser)
-
1
const_set :Parser, parser
-
end
-
-
# Return the constant located at _path_. The format of _path_ has to be
-
# either ::A::B::C or A::B::C. In any case, A has to be located at the top
-
# level (absolute namespace path?). If there doesn't exist a constant at
-
# the given path, an ArgumentError is raised.
-
1
def deep_const_get(path) # :nodoc:
-
10
path.to_s.split(/::/).inject(Object) do |p, c|
-
case
-
when c.empty? then p
-
10
when JSON.const_defined_in?(p, c) then p.const_get(c)
-
else
-
begin
-
p.const_missing(c)
-
rescue NameError => e
-
raise ArgumentError, "can't get const #{path}: #{e}"
-
end
-
10
end
-
end
-
end
-
-
# Set the module _generator_ to be used by JSON.
-
1
def generator=(generator) # :nodoc:
-
1
old, $VERBOSE = $VERBOSE, nil
-
1
@generator = generator
-
1
generator_methods = generator::GeneratorMethods
-
1
for const in generator_methods.constants
-
10
klass = deep_const_get(const)
-
10
modul = generator_methods.const_get(const)
-
10
klass.class_eval do
-
10
instance_methods(false).each do |m|
-
503
m.to_s == 'to_json' and remove_method m
-
end
-
10
include modul
-
end
-
end
-
1
self.state = generator::State
-
1
const_set :State, self.state
-
1
const_set :SAFE_STATE_PROTOTYPE, State.new
-
1
const_set :FAST_STATE_PROTOTYPE, State.new(
-
:indent => '',
-
:space => '',
-
:object_nl => "",
-
:array_nl => "",
-
:max_nesting => false
-
)
-
1
const_set :PRETTY_STATE_PROTOTYPE, State.new(
-
:indent => ' ',
-
:space => ' ',
-
:object_nl => "\n",
-
:array_nl => "\n"
-
)
-
ensure
-
1
$VERBOSE = old
-
end
-
-
# Returns the JSON generator module that is used by JSON. This is
-
# either JSON::Ext::Generator or JSON::Pure::Generator.
-
1
attr_reader :generator
-
-
# Returns the JSON generator state class that is used by JSON. This is
-
# either JSON::Ext::Generator::State or JSON::Pure::Generator::State.
-
1
attr_accessor :state
-
-
# This is create identifier, which is used to decide if the _json_create_
-
# hook of a class should be called. It defaults to 'json_class'.
-
1
attr_accessor :create_id
-
end
-
1
self.create_id = 'json_class'
-
-
1
NaN = 0.0/0
-
-
1
Infinity = 1.0/0
-
-
1
MinusInfinity = -Infinity
-
-
# The base exception for JSON errors.
-
1
class JSONError < StandardError
-
1
def self.wrap(exception)
-
obj = new("Wrapped(#{exception.class}): #{exception.message.inspect}")
-
obj.set_backtrace exception.backtrace
-
obj
-
end
-
end
-
-
# This exception is raised if a parser error occurs.
-
1
class ParserError < JSONError; end
-
-
# This exception is raised if the nesting of parsed data structures is too
-
# deep.
-
1
class NestingError < ParserError; end
-
-
# :stopdoc:
-
1
class CircularDatastructure < NestingError; end
-
# :startdoc:
-
-
# This exception is raised if a generator or unparser error occurs.
-
1
class GeneratorError < JSONError; end
-
# For backwards compatibility
-
1
UnparserError = GeneratorError
-
-
# This exception is raised if the required unicode support is missing on the
-
# system. Usually this means that the iconv library is not installed.
-
1
class MissingUnicodeSupport < JSONError; end
-
-
1
module_function
-
-
# Parse the JSON document _source_ into a Ruby data structure and return it.
-
#
-
# _opts_ can have the following
-
# keys:
-
# * *max_nesting*: The maximum depth of nesting allowed in the parsed data
-
# structures. Disable depth checking with :max_nesting => false. It defaults
-
# to 19.
-
# * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in
-
# defiance of RFC 4627 to be parsed by the Parser. This option defaults
-
# to false.
-
# * *symbolize_names*: If set to true, returns symbols for the names
-
# (keys) in a JSON object. Otherwise strings are returned. Strings are
-
# the default.
-
# * *create_additions*: If set to false, the Parser doesn't create
-
# additions even if a matching class and create_id was found. This option
-
# defaults to true.
-
# * *object_class*: Defaults to Hash
-
# * *array_class*: Defaults to Array
-
1
def parse(source, opts = {})
-
45
Parser.new(source, opts).parse
-
end
-
-
# Parse the JSON document _source_ into a Ruby data structure and return it.
-
# The bang version of the parse method defaults to the more dangerous values
-
# for the _opts_ hash, so be sure only to parse trusted _source_ documents.
-
#
-
# _opts_ can have the following keys:
-
# * *max_nesting*: The maximum depth of nesting allowed in the parsed data
-
# structures. Enable depth checking with :max_nesting => anInteger. The parse!
-
# methods defaults to not doing max depth checking: This can be dangerous
-
# if someone wants to fill up your stack.
-
# * *allow_nan*: If set to true, allow NaN, Infinity, and -Infinity in
-
# defiance of RFC 4627 to be parsed by the Parser. This option defaults
-
# to true.
-
# * *create_additions*: If set to false, the Parser doesn't create
-
# additions even if a matching class and create_id was found. This option
-
# defaults to true.
-
1
def parse!(source, opts = {})
-
opts = {
-
:max_nesting => false,
-
:allow_nan => true
-
}.update(opts)
-
Parser.new(source, opts).parse
-
end
-
-
# Generate a JSON document from the Ruby data structure _obj_ and return
-
# it. _state_ is * a JSON::State object,
-
# * or a Hash like object (responding to to_hash),
-
# * an object convertible into a hash by a to_h method,
-
# that is used as or to configure a State object.
-
#
-
# It defaults to a state object, that creates the shortest possible JSON text
-
# in one line, checks for circular data structures and doesn't allow NaN,
-
# Infinity, and -Infinity.
-
#
-
# A _state_ hash can have the following keys:
-
# * *indent*: a string used to indent levels (default: ''),
-
# * *space*: a string that is put after, a : or , delimiter (default: ''),
-
# * *space_before*: a string that is put before a : pair delimiter (default: ''),
-
# * *object_nl*: a string that is put at the end of a JSON object (default: ''),
-
# * *array_nl*: a string that is put at the end of a JSON array (default: ''),
-
# * *allow_nan*: true if NaN, Infinity, and -Infinity should be
-
# generated, otherwise an exception is thrown if these values are
-
# encountered. This options defaults to false.
-
# * *max_nesting*: The maximum depth of nesting allowed in the data
-
# structures from which JSON is to be generated. Disable depth checking
-
# with :max_nesting => false, it defaults to 19.
-
#
-
# See also the fast_generate for the fastest creation method with the least
-
# amount of sanity checks, and the pretty_generate method for some
-
# defaults for pretty output.
-
1
def generate(obj, opts = nil)
-
if State === opts
-
state, opts = opts, nil
-
else
-
state = SAFE_STATE_PROTOTYPE.dup
-
end
-
if opts
-
if opts.respond_to? :to_hash
-
opts = opts.to_hash
-
elsif opts.respond_to? :to_h
-
opts = opts.to_h
-
else
-
raise TypeError, "can't convert #{opts.class} into Hash"
-
end
-
state = state.configure(opts)
-
end
-
state.generate(obj)
-
end
-
-
# :stopdoc:
-
# I want to deprecate these later, so I'll first be silent about them, and
-
# later delete them.
-
1
alias unparse generate
-
1
module_function :unparse
-
# :startdoc:
-
-
# Generate a JSON document from the Ruby data structure _obj_ and return it.
-
# This method disables the checks for circles in Ruby objects.
-
#
-
# *WARNING*: Be careful not to pass any Ruby data structures with circles as
-
# _obj_ argument because this will cause JSON to go into an infinite loop.
-
1
def fast_generate(obj, opts = nil)
-
if State === opts
-
state, opts = opts, nil
-
else
-
state = FAST_STATE_PROTOTYPE.dup
-
end
-
if opts
-
if opts.respond_to? :to_hash
-
opts = opts.to_hash
-
elsif opts.respond_to? :to_h
-
opts = opts.to_h
-
else
-
raise TypeError, "can't convert #{opts.class} into Hash"
-
end
-
state.configure(opts)
-
end
-
state.generate(obj)
-
end
-
-
# :stopdoc:
-
# I want to deprecate these later, so I'll first be silent about them, and later delete them.
-
1
alias fast_unparse fast_generate
-
1
module_function :fast_unparse
-
# :startdoc:
-
-
# Generate a JSON document from the Ruby data structure _obj_ and return it.
-
# The returned document is a prettier form of the document returned by
-
# #unparse.
-
#
-
# The _opts_ argument can be used to configure the generator. See the
-
# generate method for a more detailed explanation.
-
1
def pretty_generate(obj, opts = nil)
-
if State === opts
-
state, opts = opts, nil
-
else
-
state = PRETTY_STATE_PROTOTYPE.dup
-
end
-
if opts
-
if opts.respond_to? :to_hash
-
opts = opts.to_hash
-
elsif opts.respond_to? :to_h
-
opts = opts.to_h
-
else
-
raise TypeError, "can't convert #{opts.class} into Hash"
-
end
-
state.configure(opts)
-
end
-
state.generate(obj)
-
end
-
-
# :stopdoc:
-
# I want to deprecate these later, so I'll first be silent about them, and later delete them.
-
1
alias pretty_unparse pretty_generate
-
1
module_function :pretty_unparse
-
# :startdoc:
-
-
1
class << self
-
# The global default options for the JSON.load method:
-
# :max_nesting: false
-
# :allow_nan: true
-
# :quirks_mode: true
-
1
attr_accessor :load_default_options
-
end
-
1
self.load_default_options = {
-
:max_nesting => false,
-
:allow_nan => true,
-
:quirks_mode => true,
-
}
-
-
# Load a ruby data structure from a JSON _source_ and return it. A source can
-
# either be a string-like object, an IO-like object, or an object responding
-
# to the read method. If _proc_ was given, it will be called with any nested
-
# Ruby object as an argument recursively in depth first order. The default
-
# options for the parser can be changed via the load_default_options method.
-
#
-
# This method is part of the implementation of the load/dump interface of
-
# Marshal and YAML.
-
1
def load(source, proc = nil)
-
opts = load_default_options
-
if source.respond_to? :to_str
-
source = source.to_str
-
elsif source.respond_to? :to_io
-
source = source.to_io.read
-
elsif source.respond_to?(:read)
-
source = source.read
-
end
-
if opts[:quirks_mode] && (source.nil? || source.empty?)
-
source = 'null'
-
end
-
result = parse(source, opts)
-
recurse_proc(result, &proc) if proc
-
result
-
end
-
-
# Recursively calls passed _Proc_ if the parsed data structure is an _Array_ or _Hash_
-
1
def recurse_proc(result, &proc)
-
case result
-
when Array
-
result.each { |x| recurse_proc x, &proc }
-
proc.call result
-
when Hash
-
result.each { |x, y| recurse_proc x, &proc; recurse_proc y, &proc }
-
proc.call result
-
else
-
proc.call result
-
end
-
end
-
-
1
alias restore load
-
1
module_function :restore
-
-
1
class << self
-
# The global default options for the JSON.dump method:
-
# :max_nesting: false
-
# :allow_nan: true
-
# :quirks_mode: true
-
1
attr_accessor :dump_default_options
-
end
-
1
self.dump_default_options = {
-
:max_nesting => false,
-
:allow_nan => true,
-
:quirks_mode => true,
-
}
-
-
# Dumps _obj_ as a JSON string, i.e. calls generate on the object and returns
-
# the result.
-
#
-
# If anIO (an IO-like object or an object that responds to the write method)
-
# was given, the resulting JSON is written to it.
-
#
-
# If the number of nested arrays or objects exceeds _limit_, an ArgumentError
-
# exception is raised. This argument is similar (but not exactly the
-
# same!) to the _limit_ argument in Marshal.dump.
-
#
-
# The default options for the generator can be changed via the
-
# dump_default_options method.
-
#
-
# This method is part of the implementation of the load/dump interface of
-
# Marshal and YAML.
-
1
def dump(obj, anIO = nil, limit = nil)
-
if anIO and limit.nil?
-
anIO = anIO.to_io if anIO.respond_to?(:to_io)
-
unless anIO.respond_to?(:write)
-
limit = anIO
-
anIO = nil
-
end
-
end
-
opts = JSON.dump_default_options
-
limit and opts.update(:max_nesting => limit)
-
result = generate(obj, opts)
-
if anIO
-
anIO.write result
-
anIO
-
else
-
result
-
end
-
rescue JSON::NestingError
-
raise ArgumentError, "exceed depth limit"
-
end
-
-
# Swap consecutive bytes of _string_ in place.
-
1
def self.swap!(string) # :nodoc:
-
0.upto(string.size / 2) do |i|
-
break unless string[2 * i + 1]
-
string[2 * i], string[2 * i + 1] = string[2 * i + 1], string[2 * i]
-
end
-
string
-
end
-
-
# Shortuct for iconv.
-
if ::String.method_defined?(:encode) &&
-
# XXX Rubinius doesn't support ruby 1.9 encoding yet
-
1
defined?(RUBY_ENGINE) && RUBY_ENGINE != 'rbx'
-
then
-
# Encodes string using Ruby's _String.encode_
-
1
def self.iconv(to, from, string)
-
string.encode(to, from)
-
end
-
else
-
require 'iconv'
-
# Encodes string using _iconv_ library
-
def self.iconv(to, from, string)
-
Iconv.conv(to, from, string)
-
end
-
end
-
-
1
if ::Object.method(:const_defined?).arity == 1
-
def self.const_defined_in?(modul, constant)
-
modul.const_defined?(constant)
-
end
-
else
-
1
def self.const_defined_in?(modul, constant)
-
11
modul.const_defined?(constant, false)
-
end
-
end
-
end
-
-
1
module ::Kernel
-
1
private
-
-
# Outputs _objs_ to STDOUT as JSON strings in the shortest form, that is in
-
# one line.
-
1
def j(*objs)
-
objs.each do |obj|
-
puts JSON::generate(obj, :allow_nan => true, :max_nesting => false)
-
end
-
nil
-
end
-
-
# Ouputs _objs_ to STDOUT as JSON strings in a pretty format, with
-
# indentation and over many lines.
-
1
def jj(*objs)
-
objs.each do |obj|
-
puts JSON::pretty_generate(obj, :allow_nan => true, :max_nesting => false)
-
end
-
nil
-
end
-
-
# If _object_ is string-like, parse the string and return the parsed result as
-
# a Ruby data structure. Otherwise, generate a JSON text from the Ruby data
-
# structure object and return it.
-
#
-
# The _opts_ argument is passed through to generate/parse respectively. See
-
# generate and parse for their documentation.
-
1
def JSON(object, *args)
-
if object.respond_to? :to_str
-
JSON.parse(object.to_str, args.first)
-
else
-
JSON.generate(object, args.first)
-
end
-
end
-
end
-
-
# Extends any Class to include _json_creatable?_ method.
-
1
class ::Class
-
# Returns true if this class can be used to create an instance
-
# from a serialised JSON string. The class has to implement a class
-
# method _json_create_ that expects a hash as first parameter. The hash
-
# should include the required data.
-
1
def json_creatable?
-
respond_to?(:json_create)
-
end
-
end
-
1
if ENV['SIMPLECOV_COVERAGE'].to_i == 1
-
require 'simplecov'
-
SimpleCov.start do
-
add_filter "/tests/"
-
end
-
end
-
1
require 'json/common'
-
-
1
module JSON
-
# This module holds all the modules/classes that implement JSON's
-
# functionality as C extensions.
-
1
module Ext
-
1
require 'json/ext/parser'
-
1
require 'json/ext/generator'
-
1
$DEBUG and warn "Using Ext extension for JSON."
-
1
JSON.parser = Parser
-
1
JSON.generator = Generator
-
end
-
-
1
JSON_LOADED = true unless defined?(::JSON::JSON_LOADED)
-
end
-
1
require 'ostruct'
-
-
1
module JSON
-
1
class GenericObject < OpenStruct
-
1
class << self
-
1
alias [] new
-
-
1
def json_create(data)
-
data = data.dup
-
data.delete JSON.create_id
-
self[data]
-
end
-
end
-
-
1
def to_hash
-
table
-
end
-
-
1
def [](name)
-
table[name.to_sym]
-
end
-
-
1
def []=(name, value)
-
__send__ "#{name}=", value
-
end
-
-
1
def |(other)
-
self.class[other.to_hash.merge(to_hash)]
-
end
-
-
1
def as_json(*)
-
{ JSON.create_id => self.class.name }.merge to_hash
-
end
-
-
1
def to_json(*a)
-
as_json.to_json(*a)
-
end
-
end
-
end
-
1
module JSON
-
# JSON version
-
1
VERSION = '1.7.5'
-
4
VERSION_ARRAY = VERSION.split(/\./).map { |x| x.to_i } # :nodoc:
-
1
VERSION_MAJOR = VERSION_ARRAY[0] # :nodoc:
-
1
VERSION_MINOR = VERSION_ARRAY[1] # :nodoc:
-
1
VERSION_BUILD = VERSION_ARRAY[2] # :nodoc:
-
end
-
1
module Metaclass
-
end
-
-
1
require "metaclass/version"
-
1
require "metaclass/object_methods"
-
1
module Metaclass::ObjectMethods
-
1
def __metaclass__
-
728
class << self
-
728
self
-
end
-
end
-
end
-
-
1
class Object
-
1
include Metaclass::ObjectMethods
-
end
-
1
module Metaclass
-
1
VERSION = "0.0.1"
-
end
-
1
begin
-
1
require 'rubygems'
-
1
gem 'minitest'
-
rescue Gem::LoadError
-
# do nothing
-
end
-
-
1
require 'minitest/unit'
-
1
require 'minitest/spec'
-
1
require 'minitest/mock'
-
-
1
MiniTest::Unit.autorun
-
1
class MockExpectationError < StandardError # :nodoc:
-
end # omg... worst bug ever. rdoc doesn't allow 1-liners
-
-
##
-
# A simple and clean mock object framework.
-
-
1
module MiniTest
-
-
##
-
# All mock objects are an instance of Mock
-
-
1
class Mock
-
1
alias :__respond_to? :respond_to?
-
-
1
skip_methods = %w(object_id respond_to_missing? inspect === to_s)
-
-
1
instance_methods.each do |m|
-
103
undef_method m unless skip_methods.include?(m.to_s) || m =~ /^__/
-
end
-
-
1
def initialize # :nodoc:
-
@expected_calls = Hash.new { |calls, name| calls[name] = [] }
-
@actual_calls = Hash.new { |calls, name| calls[name] = [] }
-
end
-
-
##
-
# Expect that method +name+ is called, optionally with +args+, and returns
-
# +retval+.
-
#
-
# @mock.expect(:meaning_of_life, 42)
-
# @mock.meaning_of_life # => 42
-
#
-
# @mock.expect(:do_something_with, true, [some_obj, true])
-
# @mock.do_something_with(some_obj, true) # => true
-
#
-
# +args+ is compared to the expected args using case equality (ie, the
-
# '===' operator), allowing for less specific expectations.
-
#
-
# @mock.expect(:uses_any_string, true, [String])
-
# @mock.uses_any_string("foo") # => true
-
# @mock.verify # => true
-
#
-
# @mock.expect(:uses_one_string, true, ["foo"]
-
# @mock.uses_one_string("bar") # => true
-
# @mock.verify # => raises MockExpectationError
-
-
1
def expect(name, retval, args=[])
-
raise ArgumentError, "args must be an array" unless Array === args
-
@expected_calls[name] << { :retval => retval, :args => args }
-
self
-
end
-
-
1
def __call name, data # :nodoc:
-
case data
-
when Hash then
-
"#{name}(#{data[:args].inspect[1..-2]}) => #{data[:retval].inspect}"
-
else
-
data.map { |d| __call name, d }.join ", "
-
end
-
end
-
-
##
-
# Verify that all methods were called as expected. Raises
-
# +MockExpectationError+ if the mock object was not called as
-
# expected.
-
-
1
def verify
-
@expected_calls.each do |name, calls|
-
calls.each do |expected|
-
msg1 = "expected #{__call name, expected}"
-
msg2 = "#{msg1}, got [#{__call name, @actual_calls[name]}]"
-
-
raise MockExpectationError, msg2 if
-
@actual_calls.has_key?(name) and
-
not @actual_calls[name].include?(expected)
-
-
raise MockExpectationError, msg1 unless
-
@actual_calls.has_key?(name) and
-
@actual_calls[name].include?(expected)
-
end
-
end
-
true
-
end
-
-
1
def method_missing(sym, *args) # :nodoc:
-
unless @expected_calls.has_key?(sym) then
-
raise NoMethodError, "unmocked method %p, expected one of %p" %
-
[sym, @expected_calls.keys.sort_by(&:to_s)]
-
end
-
-
index = @actual_calls[sym].length
-
expected_call = @expected_calls[sym][index]
-
-
unless expected_call then
-
raise MockExpectationError, "No more expects available for %p: %p" %
-
[sym, args]
-
end
-
-
expected_args, retval = expected_call[:args], expected_call[:retval]
-
-
if expected_args.size != args.size then
-
raise ArgumentError, "mocked method %p expects %d arguments, got %d" %
-
[sym, expected_args.size, args.size]
-
end
-
-
fully_matched = expected_args.zip(args).all? { |mod, a|
-
mod === a or mod == a
-
}
-
-
unless fully_matched then
-
raise MockExpectationError, "mocked method %p called with unexpected arguments %p" %
-
[sym, args]
-
end
-
-
@actual_calls[sym] << {
-
:retval => retval,
-
:args => expected_args.zip(args).map { |mod, a| mod === a ? mod : a }
-
}
-
-
retval
-
end
-
-
1
def respond_to?(sym, include_private = false) # :nodoc:
-
return true if @expected_calls.has_key?(sym.to_sym)
-
return __respond_to?(sym, include_private)
-
end
-
end
-
end
-
-
1
class Object # :nodoc:
-
-
##
-
# Add a temporary stubbed method replacing +name+ for the duration
-
# of the +block+. If +val_or_callable+ responds to #call, then it
-
# returns the result of calling it, otherwise returns the value
-
# as-is. Cleans up the stub at the end of the +block+.
-
#
-
# def test_stale_eh
-
# obj_under_test = Something.new
-
# refute obj_under_test.stale?
-
#
-
# Time.stub :now, Time.at(0) do
-
# assert obj_under_test.stale?
-
# end
-
# end
-
-
1
def stub name, val_or_callable, &block
-
new_name = "__minitest_stub__#{name}"
-
-
metaclass = class << self; self; end
-
-
if respond_to? name and not methods.map(&:to_s).include? name.to_s then
-
metaclass.send :define_method, name do |*args|
-
super(*args)
-
end
-
end
-
-
metaclass.send :alias_method, new_name, name
-
-
metaclass.send :define_method, name do |*args|
-
if val_or_callable.respond_to? :call then
-
val_or_callable.call(*args)
-
else
-
val_or_callable
-
end
-
end
-
-
yield self
-
ensure
-
metaclass.send :undef_method, name
-
metaclass.send :alias_method, name, new_name
-
metaclass.send :undef_method, new_name
-
end
-
end
-
1
class ParallelEach
-
1
require 'thread'
-
1
include Enumerable
-
-
1
N = (ENV['N'] || 2).to_i
-
-
1
def initialize list
-
1
@queue = Queue.new # *sigh*... the Queue api sucks sooo much...
-
-
1
list.each { |i| @queue << i }
-
3
N.times { @queue << nil }
-
end
-
-
1
def grep pattern
-
self.class.new super
-
end
-
-
1
def each
-
1
threads = N.times.map {
-
2
Thread.new do
-
2
Thread.current.abort_on_exception = true
-
2
while job = @queue.pop
-
yield job
-
end
-
end
-
}
-
1
threads.map(&:join)
-
end
-
end
-
#!/usr/bin/ruby -w
-
-
1
require 'minitest/unit'
-
-
1
class Module # :nodoc:
-
1
def infect_an_assertion meth, new_name, dont_flip = false # :nodoc:
-
# warn "%-22p -> %p %p" % [meth, new_name, dont_flip]
-
29
self.class_eval <<-EOM
-
def #{new_name} *args
-
case
-
when Proc === self then
-
MiniTest::Spec.current.#{meth}(*args, &self)
-
when #{!!dont_flip} then
-
MiniTest::Spec.current.#{meth}(self, *args)
-
else
-
MiniTest::Spec.current.#{meth}(args.first, self, *args[1..-1])
-
end
-
end
-
EOM
-
end
-
-
##
-
# infect_with_assertions has been removed due to excessive clever.
-
# Use infect_an_assertion directly instead.
-
-
1
def infect_with_assertions(pos_prefix, neg_prefix,
-
skip_re,
-
dont_flip_re = /\c0/,
-
map = {})
-
abort "infect_with_assertions is dead. Use infect_an_assertion directly"
-
end
-
end
-
-
1
module Kernel # :nodoc:
-
##
-
# Describe a series of expectations for a given target +desc+.
-
#
-
# TODO: find good tutorial url.
-
#
-
# Defines a test class subclassing from either MiniTest::Spec or
-
# from the surrounding describe's class. The surrounding class may
-
# subclass MiniTest::Spec manually in order to easily share code:
-
#
-
# class MySpec < MiniTest::Spec
-
# # ... shared code ...
-
# end
-
#
-
# class TestStuff < MySpec
-
# it "does stuff" do
-
# # shared code available here
-
# end
-
# describe "inner stuff" do
-
# it "still does stuff" do
-
# # ...and here
-
# end
-
# end
-
# end
-
-
1
def describe desc, additional_desc = nil, &block # :doc:
-
stack = MiniTest::Spec.describe_stack
-
name = [stack.last, desc, additional_desc].compact.join("::")
-
sclas = stack.last || if Class === self && self < MiniTest::Spec then
-
self
-
else
-
MiniTest::Spec.spec_type desc
-
end
-
-
cls = sclas.create name, desc
-
-
stack.push cls
-
cls.class_eval(&block)
-
stack.pop
-
cls
-
end
-
1
private :describe
-
end
-
-
##
-
# MiniTest::Spec -- The faster, better, less-magical spec framework!
-
#
-
# For a list of expectations, see MiniTest::Expectations.
-
-
1
class MiniTest::Spec < MiniTest::Unit::TestCase
-
##
-
# Contains pairs of matchers and Spec classes to be used to
-
# calculate the superclass of a top-level describe. This allows for
-
# automatically customizable spec types.
-
#
-
# See: register_spec_type and spec_type
-
-
1
TYPES = [[//, MiniTest::Spec]]
-
-
##
-
# Register a new type of spec that matches the spec's description.
-
# This method can take either a Regexp and a spec class or a spec
-
# class and a block that takes the description and returns true if
-
# it matches.
-
#
-
# Eg:
-
#
-
# register_spec_type(/Controller$/, MiniTest::Spec::Rails)
-
#
-
# or:
-
#
-
# register_spec_type(MiniTest::Spec::RailsModel) do |desc|
-
# desc.superclass == ActiveRecord::Base
-
# end
-
-
1
def self.register_spec_type(*args, &block)
-
1
if block then
-
1
matcher, klass = block, args.first
-
else
-
matcher, klass = *args
-
end
-
1
TYPES.unshift [matcher, klass]
-
end
-
-
##
-
# Figure out the spec class to use based on a spec's description. Eg:
-
#
-
# spec_type("BlahController") # => MiniTest::Spec::Rails
-
-
1
def self.spec_type desc
-
2
TYPES.find { |matcher, klass|
-
3
if matcher.respond_to? :call then
-
2
matcher.call desc
-
else
-
1
matcher === desc.to_s
-
end
-
}.last
-
end
-
-
1
@@describe_stack = []
-
1
def self.describe_stack # :nodoc:
-
@@describe_stack
-
end
-
-
##
-
# Returns the children of this spec.
-
-
1
def self.children
-
203
@children ||= []
-
end
-
-
1
def self.nuke_test_methods! # :nodoc:
-
self.public_instance_methods.grep(/^test_/).each do |name|
-
self.send :undef_method, name
-
end
-
end
-
-
##
-
# Define a 'before' action. Inherits the way normal methods should.
-
#
-
# NOTE: +type+ is ignored and is only there to make porting easier.
-
#
-
# Equivalent to MiniTest::Unit::TestCase#setup.
-
-
1
def self.before type = nil, &block
-
define_method :setup do
-
super()
-
self.instance_eval(&block)
-
end
-
end
-
-
##
-
# Define an 'after' action. Inherits the way normal methods should.
-
#
-
# NOTE: +type+ is ignored and is only there to make porting easier.
-
#
-
# Equivalent to MiniTest::Unit::TestCase#teardown.
-
-
1
def self.after type = nil, &block
-
define_method :teardown do
-
self.instance_eval(&block)
-
super()
-
end
-
end
-
-
##
-
# Define an expectation with name +desc+. Name gets morphed to a
-
# proper test method name. For some freakish reason, people who
-
# write specs don't like class inheritence, so this goes way out of
-
# its way to make sure that expectations aren't inherited.
-
#
-
# This is also aliased to #specify and doesn't require a +desc+ arg.
-
#
-
# Hint: If you _do_ want inheritence, use minitest/unit. You can mix
-
# and match between assertions and expectations as much as you want.
-
-
1
def self.it desc = "anonymous", &block
-
203
block ||= proc { skip "(no tests defined)" }
-
-
203
@specs ||= 0
-
203
@specs += 1
-
-
203
name = "test_%04d_%s" % [ @specs, desc ]
-
-
203
define_method name, &block
-
-
203
self.children.each do |mod|
-
mod.send :undef_method, name if mod.public_method_defined? name
-
end
-
-
203
name
-
end
-
-
##
-
# Essentially, define an accessor for +name+ with +block+.
-
#
-
# Why use let instead of def? I honestly don't know.
-
-
1
def self.let name, &block
-
define_method name do
-
@_memoized ||= {}
-
@_memoized.fetch(name) { |k| @_memoized[k] = instance_eval(&block) }
-
end
-
end
-
-
##
-
# Another lazy man's accessor generator. Made even more lazy by
-
# setting the name for you to +subject+.
-
-
1
def self.subject &block
-
let :subject, &block
-
end
-
-
1
def self.create name, desc # :nodoc:
-
cls = Class.new(self) do
-
@name = name
-
@desc = desc
-
-
nuke_test_methods!
-
end
-
-
children << cls
-
-
cls
-
end
-
-
1
def self.to_s # :nodoc:
-
7720
defined?(@name) ? @name : super
-
end
-
-
# :stopdoc:
-
1
class << self
-
1
attr_reader :desc
-
1
alias :specify :it
-
1
alias :name :to_s
-
end
-
# :startdoc:
-
end
-
-
##
-
# It's where you hide your "assertions".
-
-
1
module MiniTest::Expectations
-
##
-
# See MiniTest::Assertions#assert_empty.
-
#
-
# collection.must_be_empty
-
#
-
# :method: must_be_empty
-
-
1
infect_an_assertion :assert_empty, :must_be_empty, :unary
-
-
##
-
# See MiniTest::Assertions#assert_equal
-
#
-
# a.must_equal b
-
#
-
# :method: must_equal
-
-
1
infect_an_assertion :assert_equal, :must_equal
-
-
##
-
# See MiniTest::Assertions#assert_in_delta
-
#
-
# n.must_be_close_to m [, delta]
-
#
-
# :method: must_be_close_to
-
-
1
infect_an_assertion :assert_in_delta, :must_be_close_to
-
-
1
alias :must_be_within_delta :must_be_close_to # :nodoc:
-
-
##
-
# See MiniTest::Assertions#assert_in_epsilon
-
#
-
# n.must_be_within_epsilon m [, epsilon]
-
#
-
# :method: must_be_within_epsilon
-
-
1
infect_an_assertion :assert_in_epsilon, :must_be_within_epsilon
-
-
##
-
# See MiniTest::Assertions#assert_includes
-
#
-
# collection.must_include obj
-
#
-
# :method: must_include
-
-
1
infect_an_assertion :assert_includes, :must_include, :reverse
-
-
##
-
# See MiniTest::Assertions#assert_instance_of
-
#
-
# obj.must_be_instance_of klass
-
#
-
# :method: must_be_instance_of
-
-
1
infect_an_assertion :assert_instance_of, :must_be_instance_of
-
-
##
-
# See MiniTest::Assertions#assert_kind_of
-
#
-
# obj.must_be_kind_of mod
-
#
-
# :method: must_be_kind_of
-
-
1
infect_an_assertion :assert_kind_of, :must_be_kind_of
-
-
##
-
# See MiniTest::Assertions#assert_match
-
#
-
# a.must_match b
-
#
-
# :method: must_match
-
-
1
infect_an_assertion :assert_match, :must_match
-
-
##
-
# See MiniTest::Assertions#assert_nil
-
#
-
# obj.must_be_nil
-
#
-
# :method: must_be_nil
-
-
1
infect_an_assertion :assert_nil, :must_be_nil, :unary
-
-
##
-
# See MiniTest::Assertions#assert_operator
-
#
-
# n.must_be :<=, 42
-
#
-
# This can also do predicates:
-
#
-
# str.must_be :empty?
-
#
-
# :method: must_be
-
-
1
infect_an_assertion :assert_operator, :must_be, :reverse
-
-
##
-
# See MiniTest::Assertions#assert_output
-
#
-
# proc { ... }.must_output out_or_nil [, err]
-
#
-
# :method: must_output
-
-
1
infect_an_assertion :assert_output, :must_output
-
-
##
-
# See MiniTest::Assertions#assert_raises
-
#
-
# proc { ... }.must_raise exception
-
#
-
# :method: must_raise
-
-
1
infect_an_assertion :assert_raises, :must_raise
-
-
##
-
# See MiniTest::Assertions#assert_respond_to
-
#
-
# obj.must_respond_to msg
-
#
-
# :method: must_respond_to
-
-
1
infect_an_assertion :assert_respond_to, :must_respond_to, :reverse
-
-
##
-
# See MiniTest::Assertions#assert_same
-
#
-
# a.must_be_same_as b
-
#
-
# :method: must_be_same_as
-
-
1
infect_an_assertion :assert_same, :must_be_same_as
-
-
##
-
# See MiniTest::Assertions#assert_send
-
# TODO: remove me
-
#
-
# a.must_send
-
#
-
# :method: must_send
-
-
1
infect_an_assertion :assert_send, :must_send
-
-
##
-
# See MiniTest::Assertions#assert_silent
-
#
-
# proc { ... }.must_be_silent
-
#
-
# :method: must_be_silent
-
-
1
infect_an_assertion :assert_silent, :must_be_silent
-
-
##
-
# See MiniTest::Assertions#assert_throws
-
#
-
# proc { ... }.must_throw sym
-
#
-
# :method: must_throw
-
-
1
infect_an_assertion :assert_throws, :must_throw
-
-
##
-
# See MiniTest::Assertions#refute_empty
-
#
-
# collection.wont_be_empty
-
#
-
# :method: wont_be_empty
-
-
1
infect_an_assertion :refute_empty, :wont_be_empty, :unary
-
-
##
-
# See MiniTest::Assertions#refute_equal
-
#
-
# a.wont_equal b
-
#
-
# :method: wont_equal
-
-
1
infect_an_assertion :refute_equal, :wont_equal
-
-
##
-
# See MiniTest::Assertions#refute_in_delta
-
#
-
# n.wont_be_close_to m [, delta]
-
#
-
# :method: wont_be_close_to
-
-
1
infect_an_assertion :refute_in_delta, :wont_be_close_to
-
-
1
alias :wont_be_within_delta :wont_be_close_to # :nodoc:
-
-
##
-
# See MiniTest::Assertions#refute_in_epsilon
-
#
-
# n.wont_be_within_epsilon m [, epsilon]
-
#
-
# :method: wont_be_within_epsilon
-
-
1
infect_an_assertion :refute_in_epsilon, :wont_be_within_epsilon
-
-
##
-
# See MiniTest::Assertions#refute_includes
-
#
-
# collection.wont_include obj
-
#
-
# :method: wont_include
-
-
1
infect_an_assertion :refute_includes, :wont_include, :reverse
-
-
##
-
# See MiniTest::Assertions#refute_instance_of
-
#
-
# obj.wont_be_instance_of klass
-
#
-
# :method: wont_be_instance_of
-
-
1
infect_an_assertion :refute_instance_of, :wont_be_instance_of
-
-
##
-
# See MiniTest::Assertions#refute_kind_of
-
#
-
# obj.wont_be_kind_of mod
-
#
-
# :method: wont_be_kind_of
-
-
1
infect_an_assertion :refute_kind_of, :wont_be_kind_of
-
-
##
-
# See MiniTest::Assertions#refute_match
-
#
-
# a.wont_match b
-
#
-
# :method: wont_match
-
-
1
infect_an_assertion :refute_match, :wont_match
-
-
##
-
# See MiniTest::Assertions#refute_nil
-
#
-
# obj.wont_be_nil
-
#
-
# :method: wont_be_nil
-
-
1
infect_an_assertion :refute_nil, :wont_be_nil, :unary
-
-
##
-
# See MiniTest::Assertions#refute_operator
-
#
-
# n.wont_be :<=, 42
-
#
-
# This can also do predicates:
-
#
-
# str.wont_be :empty?
-
#
-
# :method: wont_be
-
-
1
infect_an_assertion :refute_operator, :wont_be, :reverse
-
-
##
-
# See MiniTest::Assertions#refute_respond_to
-
#
-
# obj.wont_respond_to msg
-
#
-
# :method: wont_respond_to
-
-
1
infect_an_assertion :refute_respond_to, :wont_respond_to, :reverse
-
-
##
-
# See MiniTest::Assertions#refute_same
-
#
-
# a.wont_be_same_as b
-
#
-
# :method: wont_be_same_as
-
-
1
infect_an_assertion :refute_same, :wont_be_same_as
-
end
-
-
1
class Object # :nodoc:
-
1
include MiniTest::Expectations
-
end
-
1
require 'optparse'
-
1
require 'rbconfig'
-
1
require 'thread' # required for 1.8
-
1
require 'minitest/parallel_each'
-
-
##
-
# Minimal (mostly drop-in) replacement for test-unit.
-
#
-
# :include: README.txt
-
-
1
module MiniTest
-
-
1
def self.const_missing name # :nodoc:
-
case name
-
when :MINI_DIR then
-
msg = "MiniTest::MINI_DIR was removed. Don't violate other's internals."
-
warn "WAR\NING: #{msg}"
-
warn "WAR\NING: Used by #{caller.first}."
-
const_set :MINI_DIR, "bad value"
-
else
-
super
-
end
-
end
-
-
##
-
# Assertion base class
-
-
1
class Assertion < Exception; end
-
-
##
-
# Assertion raised when skipping a test
-
-
1
class Skip < Assertion; end
-
-
1
class << self
-
1
attr_accessor :backtrace_filter
-
end
-
-
1
class BacktraceFilter # :nodoc:
-
1
def filter bt
-
175
return ["No backtrace"] unless bt
-
-
175
new_bt = []
-
-
175
unless $DEBUG then
-
175
bt.each do |line|
-
1077
break if line =~ /lib\/minitest/
-
902
new_bt << line
-
end
-
-
221
new_bt = bt.reject { |line| line =~ /lib\/minitest/ } if new_bt.empty?
-
175
new_bt = bt.dup if new_bt.empty?
-
else
-
new_bt = bt.dup
-
end
-
-
175
new_bt
-
end
-
end
-
-
1
self.backtrace_filter = BacktraceFilter.new
-
-
1
def self.filter_backtrace bt # :nodoc:
-
175
backtrace_filter.filter bt
-
end
-
-
##
-
# MiniTest Assertions. All assertion methods accept a +msg+ which is
-
# printed if the assertion fails.
-
-
1
module Assertions
-
1
UNDEFINED = Object.new # :nodoc:
-
-
1
def UNDEFINED.inspect # :nodoc:
-
"UNDEFINED" # again with the rdoc bugs... :(
-
end
-
-
##
-
# Returns the diff command to use in #diff. Tries to intelligently
-
# figure out what diff to use.
-
-
1
def self.diff
-
@diff = if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ then
-
"diff.exe -u"
-
else
-
1
if system("gdiff", __FILE__, __FILE__)
-
"gdiff -u" # solaris and kin suck
-
elsif system("diff", __FILE__, __FILE__)
-
1
"diff -u"
-
else
-
nil
-
end
-
3
end unless defined? @diff
-
-
3
@diff
-
end
-
-
##
-
# Set the diff command to use in #diff.
-
-
1
def self.diff= o
-
@diff = o
-
end
-
-
##
-
# Returns a diff between +exp+ and +act+. If there is no known
-
# diff command or if it doesn't make sense to diff the output
-
# (single line, short output), then it simply returns a basic
-
# comparison between the two.
-
-
1
def diff exp, act
-
3
require "tempfile"
-
-
3
expect = mu_pp_for_diff exp
-
3
butwas = mu_pp_for_diff act
-
3
result = nil
-
-
3
need_to_diff =
-
MiniTest::Assertions.diff &&
-
(expect.include?("\n") ||
-
3
butwas.include?("\n") ||
-
expect.size > 30 ||
-
butwas.size > 30 ||
-
expect == butwas)
-
-
return "Expected: #{mu_pp exp}\n Actual: #{mu_pp act}" unless
-
3
need_to_diff
-
-
Tempfile.open("expect") do |a|
-
a.puts expect
-
a.flush
-
-
Tempfile.open("butwas") do |b|
-
b.puts butwas
-
b.flush
-
-
result = `#{MiniTest::Assertions.diff} #{a.path} #{b.path}`
-
result.sub!(/^\-\-\- .+/, "--- expected")
-
result.sub!(/^\+\+\+ .+/, "+++ actual")
-
-
if result.empty? then
-
klass = exp.class
-
result = [
-
"No visible difference in the #{klass}#inspect output.",
-
"You should look at your implementation of #{klass}#==.",
-
expect
-
].join "\n"
-
end
-
end
-
end
-
-
result
-
end
-
-
##
-
# This returns a human-readable version of +obj+. By default
-
# #inspect is called. You can override this to use #pretty_print
-
# if you want.
-
-
1
def mu_pp obj
-
181
s = obj.inspect
-
181
s = s.encode Encoding.default_external if defined? Encoding
-
181
s
-
end
-
-
##
-
# This returns a diff-able human-readable version of +obj+. This
-
# differs from the regular mu_pp because it expands escaped
-
# newlines and makes hex-values generic (like object_ids). This
-
# uses mu_pp to do the first pass and then cleans it up.
-
-
1
def mu_pp_for_diff obj # TODO: possibly rename
-
6
mu_pp(obj).gsub(/\\n/, "\n").gsub(/0x[a-f0-9]+/m, '0xXXXXXX')
-
end
-
-
1
def _assertions= n # :nodoc:
-
12274
@_assertions = n
-
end
-
-
1
def _assertions # :nodoc:
-
15130
@_assertions ||= 0
-
end
-
-
##
-
# Fails unless +test+ is a true value.
-
-
1
def assert test, msg = nil
-
9415
msg ||= "Failed assertion, no message given."
-
9415
self._assertions += 1
-
9415
unless test then
-
20
msg = msg.call if Proc === msg
-
20
raise MiniTest::Assertion, msg
-
end
-
9395
true
-
end
-
-
##
-
# Fails unless the block returns a true value.
-
#
-
# NOTE: This method is deprecated, use assert. It will be removed
-
# on 2013-01-01."
-
-
1
def assert_block msg = nil
-
warn "NOTE: MiniTest::Unit::TestCase#assert_block is deprecated, use assert. It will be removed on 2013-01-01. Called from #{caller.first}"
-
msg = message(msg) { "Expected block to return true value" }
-
assert yield, msg
-
end
-
-
##
-
# Fails unless +obj+ is empty.
-
-
1
def assert_empty obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to be empty" }
-
assert_respond_to obj, :empty?
-
assert obj.empty?, msg
-
end
-
-
##
-
# Fails unless <tt>exp == act</tt> printing the difference between
-
# the two, if possible.
-
#
-
# If there is no visible difference but the assertion fails, you
-
# should suspect that your #== is buggy, or your inspect output is
-
# missing crucial details.
-
#
-
# For floats use assert_in_delta.
-
#
-
# See also: MiniTest::Assertions.diff
-
-
1
def assert_equal exp, act, msg = nil
-
6990
msg = message(msg, "") { diff exp, act }
-
6987
assert(exp == act, msg)
-
end
-
-
##
-
# For comparing Floats. Fails unless +exp+ and +act+ are within +delta+
-
# of each other.
-
#
-
# assert_in_delta Math::PI, (22.0 / 7.0), 0.01
-
-
1
def assert_in_delta exp, act, delta = 0.001, msg = nil
-
11
n = (exp - act).abs
-
11
msg = message(msg) { "Expected |#{exp} - #{act}| (#{n}) to be < #{delta}"}
-
11
assert delta >= n, msg
-
end
-
-
##
-
# For comparing Floats. Fails unless +exp+ and +act+ have a relative
-
# error less than +epsilon+.
-
-
1
def assert_in_epsilon a, b, epsilon = 0.001, msg = nil
-
assert_in_delta a, b, [a.abs, b.abs].min * epsilon, msg
-
end
-
-
##
-
# Fails unless +collection+ includes +obj+.
-
-
1
def assert_includes collection, obj, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(collection)} to include #{mu_pp(obj)}"
-
}
-
assert_respond_to collection, :include?
-
assert collection.include?(obj), msg
-
end
-
-
##
-
# Fails unless +obj+ is an instance of +cls+.
-
-
1
def assert_instance_of cls, obj, msg = nil
-
158
msg = message(msg) {
-
"Expected #{mu_pp(obj)} to be an instance of #{cls}, not #{obj.class}"
-
}
-
-
158
assert obj.instance_of?(cls), msg
-
end
-
-
##
-
# Fails unless +obj+ is a kind of +cls+.
-
-
1
def assert_kind_of cls, obj, msg = nil # TODO: merge with instance_of
-
57
msg = message(msg) {
-
"Expected #{mu_pp(obj)} to be a kind of #{cls}, not #{obj.class}" }
-
-
57
assert obj.kind_of?(cls), msg
-
end
-
-
##
-
# Fails unless +matcher+ <tt>=~</tt> +obj+.
-
-
1
def assert_match matcher, obj, msg = nil
-
252
msg = message(msg) { "Expected #{mu_pp matcher} to match #{mu_pp obj}" }
-
252
assert_respond_to matcher, :"=~"
-
252
matcher = Regexp.new Regexp.escape matcher if String === matcher
-
252
assert matcher =~ obj, msg
-
end
-
-
##
-
# Fails unless +obj+ is nil
-
-
1
def assert_nil obj, msg = nil
-
142
msg = message(msg) { "Expected #{mu_pp(obj)} to be nil" }
-
142
assert obj.nil?, msg
-
end
-
-
##
-
# For testing with binary operators.
-
#
-
# assert_operator 5, :<=, 4
-
-
1
def assert_operator o1, op, o2 = UNDEFINED, msg = nil
-
return assert_predicate o1, op, msg if UNDEFINED == o2
-
msg = message(msg) { "Expected #{mu_pp(o1)} to be #{op} #{mu_pp(o2)}" }
-
assert o1.__send__(op, o2), msg
-
end
-
-
##
-
# Fails if stdout or stderr do not output the expected results.
-
# Pass in nil if you don't care about that streams output. Pass in
-
# "" if you require it to be silent. Pass in a regexp if you want
-
# to pattern match.
-
#
-
# NOTE: this uses #capture_io, not #capture_subprocess_io.
-
#
-
# See also: #assert_silent
-
-
1
def assert_output stdout = nil, stderr = nil
-
out, err = capture_io do
-
yield
-
end
-
-
err_msg = Regexp === stderr ? :assert_match : :assert_equal if stderr
-
out_msg = Regexp === stdout ? :assert_match : :assert_equal if stdout
-
-
y = send err_msg, stderr, err, "In stderr" if err_msg
-
x = send out_msg, stdout, out, "In stdout" if out_msg
-
-
(!stdout || x) && (!stderr || y)
-
end
-
-
##
-
# For testing with predicates.
-
#
-
# assert_predicate str, :empty?
-
#
-
# This is really meant for specs and is front-ended by assert_operator:
-
#
-
# str.must_be :empty?
-
-
1
def assert_predicate o1, op, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(o1)} to be #{op}" }
-
assert o1.__send__(op), msg
-
end
-
-
##
-
# Fails unless the block raises one of +exp+. Returns the
-
# exception matched so you can check the message, attributes, etc.
-
-
1
def assert_raises *exp
-
169
msg = "#{exp.pop}.\n" if String === exp.last
-
-
169
should_raise = false
-
169
begin
-
169
yield
-
should_raise = true
-
rescue MiniTest::Skip => e
-
details = "#{msg}#{mu_pp(exp)} exception expected, not"
-
-
if exp.include? MiniTest::Skip then
-
return e
-
else
-
raise e
-
end
-
rescue Exception => e
-
169
details = "#{msg}#{mu_pp(exp)} exception expected, not"
-
assert(exp.any? { |ex|
-
169
ex.instance_of?(Module) ? e.kind_of?(ex) : ex == e.class
-
169
}, exception_details(e, details))
-
-
169
return e
-
end
-
-
exp = exp.first if exp.size == 1
-
flunk "#{msg}#{mu_pp(exp)} expected but nothing was raised." if
-
should_raise
-
end
-
-
##
-
# Fails unless +obj+ responds to +meth+.
-
-
1
def assert_respond_to obj, meth, msg = nil
-
440
msg = message(msg) {
-
"Expected #{mu_pp(obj)} (#{obj.class}) to respond to ##{meth}"
-
}
-
440
assert obj.respond_to?(meth), msg
-
end
-
-
##
-
# Fails unless +exp+ and +act+ are #equal?
-
-
1
def assert_same exp, act, msg = nil
-
4
msg = message(msg) {
-
data = [mu_pp(act), act.object_id, mu_pp(exp), exp.object_id]
-
"Expected %s (oid=%d) to be the same as %s (oid=%d)" % data
-
}
-
4
assert exp.equal?(act), msg
-
end
-
-
##
-
# +send_ary+ is a receiver, message and arguments.
-
#
-
# Fails unless the call returns a true value
-
# TODO: I should prolly remove this from specs
-
-
1
def assert_send send_ary, m = nil
-
recv, msg, *args = send_ary
-
m = message(m) {
-
"Expected #{mu_pp(recv)}.#{msg}(*#{mu_pp(args)}) to return true" }
-
assert recv.__send__(msg, *args), m
-
end
-
-
##
-
# Fails if the block outputs anything to stderr or stdout.
-
#
-
# See also: #assert_output
-
-
1
def assert_silent
-
assert_output "", "" do
-
yield
-
end
-
end
-
-
##
-
# Fails unless the block throws +sym+
-
-
1
def assert_throws sym, msg = nil
-
default = "Expected #{mu_pp(sym)} to have been thrown"
-
caught = true
-
catch(sym) do
-
begin
-
yield
-
rescue ThreadError => e # wtf?!? 1.8 + threads == suck
-
default += ", not :#{e.message[/uncaught throw \`(\w+?)\'/, 1]}"
-
rescue ArgumentError => e # 1.9 exception
-
default += ", not #{e.message.split(/ /).last}"
-
rescue NameError => e # 1.8 exception
-
default += ", not #{e.name.inspect}"
-
end
-
caught = false
-
end
-
-
assert caught, message(msg) { default }
-
end
-
-
##
-
# Captures $stdout and $stderr into strings:
-
#
-
# out, err = capture_io do
-
# puts "Some info"
-
# warn "You did a bad thing"
-
# end
-
#
-
# assert_match %r%info%, out
-
# assert_match %r%bad%, err
-
#
-
# NOTE: For efficiency, this method uses StringIO and does not
-
# capture IO for subprocesses. Use #capture_subprocess_io for
-
# that.
-
-
1
def capture_io
-
require 'stringio'
-
-
captured_stdout, captured_stderr = StringIO.new, StringIO.new
-
-
synchronize do
-
orig_stdout, orig_stderr = $stdout, $stderr
-
$stdout, $stderr = captured_stdout, captured_stderr
-
-
begin
-
yield
-
ensure
-
$stdout = orig_stdout
-
$stderr = orig_stderr
-
end
-
end
-
-
return captured_stdout.string, captured_stderr.string
-
end
-
-
##
-
# Captures $stdout and $stderr into strings, using Tempfile to
-
# ensure that subprocess IO is captured as well.
-
#
-
# out, err = capture_subprocess_io do
-
# system "echo Some info"
-
# system "echo You did a bad thing 1>&2"
-
# end
-
#
-
# assert_match %r%info%, out
-
# assert_match %r%bad%, err
-
#
-
# NOTE: This method is approximately 10x slower than #capture_io so
-
# only use it when you need to test the output of a subprocess.
-
-
1
def capture_subprocess_io
-
require 'tempfile'
-
-
captured_stdout, captured_stderr = Tempfile.new("out"), Tempfile.new("err")
-
-
synchronize do
-
orig_stdout, orig_stderr = $stdout.dup, $stderr.dup
-
$stdout.reopen captured_stdout
-
$stderr.reopen captured_stderr
-
-
begin
-
yield
-
-
$stdout.rewind
-
$stderr.rewind
-
-
[captured_stdout.read, captured_stderr.read]
-
ensure
-
captured_stdout.unlink
-
captured_stderr.unlink
-
$stdout.reopen orig_stdout
-
$stderr.reopen orig_stderr
-
end
-
end
-
end
-
-
##
-
# Returns details for exception +e+
-
-
1
def exception_details e, msg
-
[
-
169
"#{msg}",
-
"Class: <#{e.class}>",
-
"Message: <#{e.message.inspect}>",
-
"---Backtrace---",
-
"#{MiniTest::filter_backtrace(e.backtrace).join("\n")}",
-
"---------------",
-
].join "\n"
-
end
-
-
##
-
# Fails with +msg+
-
-
1
def flunk msg = nil
-
msg ||= "Epic Fail!"
-
assert false, msg
-
end
-
-
##
-
# Returns a proc that will output +msg+ along with the default message.
-
-
1
def message msg = nil, ending = ".", &default
-
8082
proc {
-
3
custom_message = "#{msg}.\n" unless msg.nil? or msg.to_s.empty?
-
3
"#{custom_message}#{default.call}#{ending}"
-
}
-
end
-
-
##
-
# used for counting assertions
-
-
1
def pass msg = nil
-
assert true
-
end
-
-
##
-
# Fails if +test+ is a true value
-
-
1
def refute test, msg = nil
-
33
msg ||= "Failed refutation, no message given"
-
33
not assert(! test, msg)
-
end
-
-
##
-
# Fails if +obj+ is empty.
-
-
1
def refute_empty obj, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to not be empty" }
-
assert_respond_to obj, :empty?
-
refute obj.empty?, msg
-
end
-
-
##
-
# Fails if <tt>exp == act</tt>.
-
#
-
# For floats use refute_in_delta.
-
-
1
def refute_equal exp, act, msg = nil
-
26
msg = message(msg) {
-
"Expected #{mu_pp(act)} to not be equal to #{mu_pp(exp)}"
-
}
-
26
refute exp == act, msg
-
end
-
-
##
-
# For comparing Floats. Fails if +exp+ is within +delta+ of +act+.
-
#
-
# refute_in_delta Math::PI, (22.0 / 7.0)
-
-
1
def refute_in_delta exp, act, delta = 0.001, msg = nil
-
n = (exp - act).abs
-
msg = message(msg) {
-
"Expected |#{exp} - #{act}| (#{n}) to not be < #{delta}"
-
}
-
refute delta > n, msg
-
end
-
-
##
-
# For comparing Floats. Fails if +exp+ and +act+ have a relative error
-
# less than +epsilon+.
-
-
1
def refute_in_epsilon a, b, epsilon = 0.001, msg = nil
-
refute_in_delta a, b, a * epsilon, msg
-
end
-
-
##
-
# Fails if +collection+ includes +obj+.
-
-
1
def refute_includes collection, obj, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(collection)} to not include #{mu_pp(obj)}"
-
}
-
assert_respond_to collection, :include?
-
refute collection.include?(obj), msg
-
end
-
-
##
-
# Fails if +obj+ is an instance of +cls+.
-
-
1
def refute_instance_of cls, obj, msg = nil
-
msg = message(msg) {
-
"Expected #{mu_pp(obj)} to not be an instance of #{cls}"
-
}
-
refute obj.instance_of?(cls), msg
-
end
-
-
##
-
# Fails if +obj+ is a kind of +cls+.
-
-
1
def refute_kind_of cls, obj, msg = nil # TODO: merge with instance_of
-
msg = message(msg) { "Expected #{mu_pp(obj)} to not be a kind of #{cls}" }
-
refute obj.kind_of?(cls), msg
-
end
-
-
##
-
# Fails if +matcher+ <tt>=~</tt> +obj+.
-
-
1
def refute_match matcher, obj, msg = nil
-
1
msg = message(msg) {"Expected #{mu_pp matcher} to not match #{mu_pp obj}"}
-
1
assert_respond_to matcher, :"=~"
-
1
matcher = Regexp.new Regexp.escape matcher if String === matcher
-
1
refute matcher =~ obj, msg
-
end
-
-
##
-
# Fails if +obj+ is nil.
-
-
1
def refute_nil obj, msg = nil
-
3
msg = message(msg) { "Expected #{mu_pp(obj)} to not be nil" }
-
3
refute obj.nil?, msg
-
end
-
-
##
-
# Fails if +o1+ is not +op+ +o2+. Eg:
-
#
-
# refute_operator 1, :>, 2 #=> pass
-
# refute_operator 1, :<, 2 #=> fail
-
-
1
def refute_operator o1, op, o2 = UNDEFINED, msg = nil
-
return refute_predicate o1, op, msg if UNDEFINED == o2
-
msg = message(msg) { "Expected #{mu_pp(o1)} to not be #{op} #{mu_pp(o2)}"}
-
refute o1.__send__(op, o2), msg
-
end
-
-
##
-
# For testing with predicates.
-
#
-
# refute_predicate str, :empty?
-
#
-
# This is really meant for specs and is front-ended by refute_operator:
-
#
-
# str.wont_be :empty?
-
-
1
def refute_predicate o1, op, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(o1)} to not be #{op}" }
-
refute o1.__send__(op), msg
-
end
-
-
##
-
# Fails if +obj+ responds to the message +meth+.
-
-
1
def refute_respond_to obj, meth, msg = nil
-
msg = message(msg) { "Expected #{mu_pp(obj)} to not respond to #{meth}" }
-
-
refute obj.respond_to?(meth), msg
-
end
-
-
##
-
# Fails if +exp+ is the same (by object identity) as +act+.
-
-
1
def refute_same exp, act, msg = nil
-
1
msg = message(msg) {
-
data = [mu_pp(act), act.object_id, mu_pp(exp), exp.object_id]
-
"Expected %s (oid=%d) to not be the same as %s (oid=%d)" % data
-
}
-
1
refute exp.equal?(act), msg
-
end
-
-
##
-
# Skips the current test. Gets listed at the end of the run but
-
# doesn't cause a failure exit code.
-
-
1
def skip msg = nil, bt = caller
-
1
msg ||= "Skipped, no message given"
-
1
raise MiniTest::Skip, msg, bt
-
end
-
-
##
-
# Takes a block and wraps it with the runner's shared mutex.
-
-
1
def synchronize
-
Minitest::Unit.runner.synchronize do
-
yield
-
end
-
end
-
end
-
-
1
class Unit # :nodoc:
-
1
VERSION = "4.2.0" # :nodoc:
-
-
1
attr_accessor :report, :failures, :errors, :skips # :nodoc:
-
1
attr_accessor :test_count, :assertion_count # :nodoc:
-
1
attr_accessor :start_time # :nodoc:
-
1
attr_accessor :help # :nodoc:
-
1
attr_accessor :verbose # :nodoc:
-
1
attr_writer :options # :nodoc:
-
-
##
-
# Lazy accessor for options.
-
-
1
def options
-
166
@options ||= {}
-
end
-
-
1
@@installed_at_exit ||= false
-
1
@@out = $stdout
-
1
@@after_tests = []
-
-
##
-
# A simple hook allowing you to run a block of code after _all_ of
-
# the tests are done. Eg:
-
#
-
# MiniTest::Unit.after_tests { p $debugging_info }
-
-
1
def self.after_tests &block
-
@@after_tests << block
-
end
-
-
##
-
# Registers MiniTest::Unit to run tests at process exit
-
-
1
def self.autorun
-
at_exit {
-
1
next if $! # don't run if there was an exception
-
-
# the order here is important. The at_exit handler must be
-
# installed before anyone else gets a chance to install their
-
# own, that way we can be assured that our exit will be last
-
# to run (at_exit stacks).
-
1
exit_code = nil
-
-
1
at_exit {
-
1
@@after_tests.reverse_each(&:call)
-
1
exit false if exit_code && exit_code != 0
-
}
-
-
1
exit_code = MiniTest::Unit.new.run ARGV
-
1
} unless @@installed_at_exit
-
1
@@installed_at_exit = true
-
end
-
-
##
-
# Returns the stream to use for output.
-
-
1
def self.output
-
2880
@@out
-
end
-
-
##
-
# Sets MiniTest::Unit to write output to +stream+. $stdout is the default
-
# output
-
-
1
def self.output= stream
-
@@out = stream
-
end
-
-
##
-
# Tells MiniTest::Unit to delegate to +runner+, an instance of a
-
# MiniTest::Unit subclass, when MiniTest::Unit#run is called.
-
-
1
def self.runner= runner
-
@@runner = runner
-
end
-
-
##
-
# Returns the MiniTest::Unit subclass instance that will be used
-
# to run the tests. A MiniTest::Unit instance is the default
-
# runner.
-
-
1
def self.runner
-
1
@@runner ||= self.new
-
end
-
-
##
-
# Return all plugins' run methods (methods that start with "run_").
-
-
1
def self.plugins
-
@@plugins ||= (["run_tests"] +
-
public_instance_methods(false).
-
2
grep(/^run_/).map { |s| s.to_s }).uniq
-
end
-
-
##
-
# Return the IO for output.
-
-
1
def output
-
2880
self.class.output
-
end
-
-
1
def puts *a # :nodoc:
-
16
output.puts(*a)
-
end
-
-
1
def print *a # :nodoc:
-
2859
output.print(*a)
-
end
-
-
##
-
# Runner for a given +type+ (eg, test vs bench).
-
-
1
def _run_anything type
-
1
suites = TestCase.send "#{type}_suites"
-
1
return if suites.empty?
-
-
1
start = Time.now
-
-
1
puts
-
1
puts "# Running #{type}s:"
-
1
puts
-
-
1
@test_count, @assertion_count = 0, 0
-
1
sync = output.respond_to? :"sync=" # stupid emacs
-
1
old_sync, output.sync = output.sync, true if sync
-
-
1
results = _run_suites suites, type
-
-
167
@test_count = results.inject(0) { |sum, (tc, _)| sum + tc }
-
167
@assertion_count = results.inject(0) { |sum, (_, ac)| sum + ac }
-
-
1
output.sync = old_sync if sync
-
-
1
t = Time.now - start
-
-
1
puts
-
1
puts
-
puts "Finished #{type}s in %.6fs, %.4f tests/s, %.4f assertions/s." %
-
1
[t, test_count / t, assertion_count / t]
-
-
1
report.each_with_index do |msg, i|
-
8
puts "\n%3d) %s" % [i + 1, msg]
-
end
-
-
1
puts
-
-
1
status
-
end
-
-
##
-
# Runs all the +suites+ for a given +type+. Runs suites declaring
-
# a test_order of +:parallel+ in parallel, and everything else
-
# serial.
-
-
1
def _run_suites suites, type
-
167
parallel, serial = suites.partition { |s| s.test_order == :parallel }
-
-
ParallelEach.new(parallel).map { |suite| _run_suite suite, type } +
-
167
serial.map { |suite| _run_suite suite, type }
-
end
-
-
##
-
# Run a single +suite+ for a given +type+.
-
-
1
def _run_suite suite, type
-
166
header = "#{type}_suite_header"
-
166
puts send(header, suite) if respond_to? header
-
-
166
filter = options[:filter] || '/./'
-
166
filter = Regexp.new $1 if filter =~ /\/(.*)\//
-
-
166
assertions = suite.send("#{type}_methods").grep(filter).map { |method|
-
2859
inst = suite.new method
-
2859
inst._assertions = 0
-
-
2859
print "#{suite}##{method} = " if @verbose
-
-
2859
start_time = Time.now if @verbose
-
2859
result = inst.run self
-
-
2859
print "%.2f s = " % (Time.now - start_time) if @verbose
-
2859
print result
-
2859
puts if @verbose
-
-
2859
inst._assertions
-
}
-
-
3025
return assertions.size, assertions.inject(0) { |sum, n| sum + n }
-
end
-
-
##
-
# Record the result of a single run. Makes it very easy to gather
-
# information. Eg:
-
#
-
# class StatisticsRecorder < MiniTest::Unit
-
# def record suite, method, assertions, time, error
-
# # ... record the results somewhere ...
-
# end
-
# end
-
#
-
# MiniTest::Unit.runner = StatisticsRecorder.new
-
-
1
def record suite, method, assertions, time, error
-
end
-
-
1
def location e # :nodoc:
-
2
last_before_assertion = ""
-
2
e.backtrace.reverse_each do |s|
-
32
break if s =~ /in .(assert|refute|flunk|pass|fail|raise|must|wont)/
-
30
last_before_assertion = s
-
end
-
2
last_before_assertion.sub(/:in .*$/, '')
-
end
-
-
##
-
# Writes status for failed test +meth+ in +klass+ which finished with
-
# exception +e+
-
-
1
def puke klass, meth, e
-
9
e = case e
-
when MiniTest::Skip then
-
1
@skips += 1
-
1
return "S" unless @verbose
-
"Skipped:\n#{meth}(#{klass}) [#{location e}]:\n#{e.message}\n"
-
when MiniTest::Assertion then
-
2
@failures += 1
-
2
"Failure:\n#{meth}(#{klass}) [#{location e}]:\n#{e.message}\n"
-
else
-
6
@errors += 1
-
6
bt = MiniTest::filter_backtrace(e.backtrace).join "\n "
-
6
"Error:\n#{meth}(#{klass}):\n#{e.class}: #{e.message}\n #{bt}\n"
-
end
-
8
@report << e
-
8
e[0, 1]
-
end
-
-
1
def initialize # :nodoc:
-
2
@report = []
-
2
@errors = @failures = @skips = 0
-
2
@verbose = false
-
2
@mutex = Mutex.new
-
end
-
-
1
def synchronize # :nodoc:
-
@mutex.synchronize { yield }
-
end
-
-
1
def process_args args = [] # :nodoc:
-
1
options = {}
-
1
orig_args = args.dup
-
-
1
OptionParser.new do |opts|
-
1
opts.banner = 'minitest options:'
-
1
opts.version = MiniTest::Unit::VERSION
-
-
1
opts.on '-h', '--help', 'Display this help.' do
-
puts opts
-
exit
-
end
-
-
1
opts.on '-s', '--seed SEED', Integer, "Sets random seed" do |m|
-
options[:seed] = m.to_i
-
end
-
-
1
opts.on '-v', '--verbose', "Verbose. Show progress processing files." do
-
options[:verbose] = true
-
end
-
-
1
opts.on '-n', '--name PATTERN', "Filter test names on pattern (e.g. /foo/)" do |a|
-
options[:filter] = a
-
end
-
-
1
opts.parse! args
-
1
orig_args -= args
-
end
-
-
1
unless options[:seed] then
-
1
srand
-
1
options[:seed] = srand % 0xFFFF
-
1
orig_args << "--seed" << options[:seed].to_s
-
end
-
-
1
srand options[:seed]
-
-
1
self.verbose = options[:verbose]
-
3
@help = orig_args.map { |s| s =~ /[\s|&<>$()]/ ? s.inspect : s }.join " "
-
-
1
options
-
end
-
-
##
-
# Begins the full test run. Delegates to +runner+'s #_run method.
-
-
1
def run args = []
-
1
self.class.runner._run(args)
-
end
-
-
##
-
# Top level driver, controls all output and filtering.
-
-
1
def _run args = []
-
1
self.options = process_args args
-
-
1
puts "Run options: #{help}"
-
-
1
self.class.plugins.each do |plugin|
-
1
send plugin
-
1
break unless report.empty?
-
end
-
-
1
return failures + errors if @test_count > 0 # or return nil...
-
rescue Interrupt
-
abort 'Interrupted'
-
end
-
-
##
-
# Runs test suites matching +filter+.
-
-
1
def run_tests
-
1
_run_anything :test
-
end
-
-
##
-
# Writes status to +io+
-
-
1
def status io = self.output
-
1
format = "%d tests, %d assertions, %d failures, %d errors, %d skips"
-
1
io.puts format % [test_count, assertion_count, failures, errors, skips]
-
end
-
-
##
-
# Provides a simple set of guards that you can use in your tests
-
# to skip execution if it is not applicable. These methods are
-
# mixed into TestCase as both instance and class methods so you
-
# can use them inside or outside of the test methods.
-
#
-
# def test_something_for_mri
-
# skip "bug 1234" if jruby?
-
# # ...
-
# end
-
#
-
# if windows? then
-
# # ... lots of test methods ...
-
# end
-
-
1
module Guard
-
-
##
-
# Is this running on jruby?
-
-
1
def jruby? platform = RUBY_PLATFORM
-
"java" == platform
-
end
-
-
##
-
# Is this running on mri?
-
-
1
def mri? platform = RUBY_DESCRIPTION
-
/^ruby/ =~ platform
-
end
-
-
##
-
# Is this running on rubinius?
-
-
1
def rubinius? platform = defined?(RUBY_ENGINE) && RUBY_ENGINE
-
"rbx" == platform
-
end
-
-
##
-
# Is this running on windows?
-
-
1
def windows? platform = RUBY_PLATFORM
-
/mswin|mingw/ =~ platform
-
end
-
end
-
-
##
-
# Provides before/after hooks for setup and teardown. These are
-
# meant for library writers, NOT for regular test authors. See
-
# #before_setup for an example.
-
-
1
module LifecycleHooks
-
##
-
# Runs before every test, after setup. This hook is meant for
-
# libraries to extend minitest. It is not meant to be used by
-
# test developers.
-
#
-
# See #before_setup for an example.
-
-
1
def after_setup; end
-
-
##
-
# Runs before every test, before setup. This hook is meant for
-
# libraries to extend minitest. It is not meant to be used by
-
# test developers.
-
#
-
# As a simplistic example:
-
#
-
# module MyMinitestPlugin
-
# def before_setup
-
# super
-
# # ... stuff to do before setup is run
-
# end
-
#
-
# def after_setup
-
# # ... stuff to do after setup is run
-
# super
-
# end
-
#
-
# def before_teardown
-
# super
-
# # ... stuff to do before teardown is run
-
# end
-
#
-
# def after_teardown
-
# # ... stuff to do after teardown is run
-
# super
-
# end
-
# end
-
#
-
# class MiniTest::Unit::TestCase
-
# include MyMinitestPlugin
-
# end
-
-
1
def before_setup; end
-
-
##
-
# Runs after every test, before teardown. This hook is meant for
-
# libraries to extend minitest. It is not meant to be used by
-
# test developers.
-
#
-
# See #before_setup for an example.
-
-
1
def before_teardown; end
-
-
##
-
# Runs after every test, after teardown. This hook is meant for
-
# libraries to extend minitest. It is not meant to be used by
-
# test developers.
-
#
-
# See #before_setup for an example.
-
-
1
def after_teardown; end
-
end
-
-
1
module Deprecated # :nodoc:
-
-
##
-
# This entire module is deprecated and slated for removal on 2013-01-01.
-
-
1
module Hooks
-
1
def run_setup_hooks # :nodoc:
-
_run_hooks self.class.setup_hooks
-
end
-
-
1
def _run_hooks hooks # :nodoc:
-
hooks.each do |hook|
-
if hook.respond_to?(:arity) && hook.arity == 1
-
hook.call(self)
-
else
-
hook.call
-
end
-
end
-
end
-
-
1
def run_teardown_hooks # :nodoc:
-
_run_hooks self.class.teardown_hooks.reverse
-
end
-
end
-
-
##
-
# This entire module is deprecated and slated for removal on 2013-01-01.
-
-
1
module HooksCM
-
##
-
# Adds a block of code that will be executed before every
-
# TestCase is run.
-
#
-
# NOTE: This method is deprecated, use before/after_setup. It
-
# will be removed on 2013-01-01.
-
-
1
def add_setup_hook arg=nil, &block
-
warn "NOTE: MiniTest::Unit::TestCase.add_setup_hook is deprecated, use before/after_setup via a module (and call super!). It will be removed on 2013-01-01. Called from #{caller.first}"
-
hook = arg || block
-
@setup_hooks << hook
-
end
-
-
1
def setup_hooks # :nodoc:
-
if superclass.respond_to? :setup_hooks then
-
superclass.setup_hooks
-
else
-
[]
-
end + @setup_hooks
-
end
-
-
##
-
# Adds a block of code that will be executed after every
-
# TestCase is run.
-
#
-
# NOTE: This method is deprecated, use before/after_teardown. It
-
# will be removed on 2013-01-01.
-
-
1
def add_teardown_hook arg=nil, &block
-
warn "NOTE: MiniTest::Unit::TestCase#add_teardown_hook is deprecated, use before/after_teardown. It will be removed on 2013-01-01. Called from #{caller.first}"
-
hook = arg || block
-
@teardown_hooks << hook
-
end
-
-
1
def teardown_hooks # :nodoc:
-
if superclass.respond_to? :teardown_hooks then
-
superclass.teardown_hooks
-
else
-
[]
-
end + @teardown_hooks
-
end
-
end
-
end
-
-
##
-
# Subclass TestCase to create your own tests. Typically you'll want a
-
# TestCase subclass per implementation class.
-
#
-
# See MiniTest::Assertions
-
-
1
class TestCase
-
1
include LifecycleHooks
-
1
include Deprecated::Hooks
-
1
extend Deprecated::HooksCM # UGH... I can't wait 'til 2013!
-
1
include Guard
-
1
extend Guard
-
-
1
attr_reader :__name__ # :nodoc:
-
-
1
PASSTHROUGH_EXCEPTIONS = [NoMemoryError, SignalException,
-
Interrupt, SystemExit] # :nodoc:
-
-
1
SUPPORTS_INFO_SIGNAL = Signal.list['INFO'] # :nodoc:
-
-
##
-
# Runs the tests reporting the status to +runner+
-
-
1
def run runner
-
trap "INFO" do
-
runner.report.each_with_index do |msg, i|
-
warn "\n%3d) %s" % [i + 1, msg]
-
end
-
warn ''
-
time = runner.start_time ? Time.now - runner.start_time : 0
-
warn "Current Test: %s#%s %.2fs" % [self.class, self.__name__, time]
-
runner.status $stderr
-
2858
end if SUPPORTS_INFO_SIGNAL
-
-
2858
start_time = Time.now
-
-
2858
result = ""
-
2858
begin
-
2858
@passed = nil
-
2858
self.before_setup
-
2856
self.setup
-
2856
self.after_setup
-
2856
self.run_test self.__name__
-
2846
result = "." unless io?
-
2846
time = Time.now - start_time
-
2846
runner.record self.class, self.__name__, self._assertions, time, nil
-
2846
@passed = true
-
rescue *PASSTHROUGH_EXCEPTIONS
-
2
raise
-
rescue Exception => e
-
10
@passed = false
-
10
time = Time.now - start_time
-
10
runner.record self.class, self.__name__, self._assertions, time, e
-
10
result = runner.puke self.class, self.__name__, e
-
ensure
-
2858
%w{ before_teardown teardown after_teardown }.each do |hook|
-
8574
begin
-
8574
self.send hook
-
rescue *PASSTHROUGH_EXCEPTIONS
-
1
raise
-
rescue Exception => e
-
1
@passed = false
-
1
result = runner.puke self.class, self.__name__, e
-
end
-
end
-
2857
trap 'INFO', 'DEFAULT' if SUPPORTS_INFO_SIGNAL
-
end
-
2855
result
-
end
-
-
1
alias :run_test :__send__
-
-
1
def initialize name # :nodoc:
-
2864
@__name__ = name
-
2864
@__io__ = nil
-
2864
@passed = nil
-
2864
@@current = self
-
end
-
-
1
def self.current # :nodoc:
-
@@current
-
end
-
-
##
-
# Return the output IO object
-
-
1
def io
-
@__io__ = true
-
MiniTest::Unit.output
-
end
-
-
##
-
# Have we hooked up the IO yet?
-
-
1
def io?
-
2846
@__io__
-
end
-
-
1
def self.reset # :nodoc:
-
1
@@test_suites = {}
-
end
-
-
1
reset
-
-
##
-
# Call this at the top of your tests when you absolutely
-
# positively need to have ordered tests. In doing so, you're
-
# admitting that you suck and your tests are weak.
-
-
1
def self.i_suck_and_my_tests_are_order_dependent!
-
class << self
-
undef_method :test_order if method_defined? :test_order
-
define_method :test_order do :alpha end
-
end
-
end
-
-
##
-
# Make diffs for this TestCase use #pretty_inspect so that diff
-
# in assert_equal can be more details. NOTE: this is much slower
-
# than the regular inspect but much more usable for complex
-
# objects.
-
-
1
def self.make_my_diffs_pretty!
-
require 'pp'
-
-
define_method :mu_pp do |o|
-
o.pretty_inspect
-
end
-
end
-
-
##
-
# Call this at the top of your tests when you want to run your
-
# tests in parallel. In doing so, you're admitting that you rule
-
# and your tests are awesome.
-
-
1
def self.parallelize_me!
-
class << self
-
undef_method :test_order if method_defined? :test_order
-
define_method :test_order do :parallel end
-
end
-
end
-
-
1
def self.inherited klass # :nodoc:
-
171
@@test_suites[klass] = true
-
171
klass.reset_setup_teardown_hooks
-
171
super
-
end
-
-
1
def self.test_order # :nodoc:
-
2
:random
-
end
-
-
1
def self.test_suites # :nodoc:
-
167
@@test_suites.keys.sort_by { |ts| ts.name.to_s }
-
end
-
-
1
def self.test_methods # :nodoc:
-
3025
methods = public_instance_methods(true).grep(/^test/).map { |m| m.to_s }
-
-
166
case self.test_order
-
when :parallel
-
max = methods.size
-
ParallelEach.new methods.sort.sort_by { rand max }
-
when :random then
-
1
max = methods.size
-
1
methods.sort.sort_by { rand max }
-
when :alpha, :sorted then
-
165
methods.sort
-
else
-
raise "Unknown test_order: #{self.test_order.inspect}"
-
end
-
end
-
-
##
-
# Returns true if the test passed.
-
-
1
def passed?
-
@passed
-
end
-
-
##
-
# Runs before every test. Use this to set up before each test
-
# run.
-
-
1
def setup; end
-
-
##
-
# Runs after every test. Use this to clean up after each test
-
# run.
-
-
1
def teardown; end
-
-
1
def self.reset_setup_teardown_hooks # :nodoc:
-
# also deprecated... believe it.
-
172
@setup_hooks = []
-
172
@teardown_hooks = []
-
end
-
-
1
reset_setup_teardown_hooks
-
-
1
include MiniTest::Assertions
-
end # class TestCase
-
end # class Unit
-
end # module MiniTest
-
-
1
Minitest = MiniTest # :nodoc: because ugh... I typo this all the time
-
-
1
if $DEBUG then
-
module Test # :nodoc:
-
module Unit # :nodoc:
-
class TestCase # :nodoc:
-
def self.inherited x # :nodoc:
-
# this helps me ferret out porting issues
-
raise "Using minitest and test/unit in the same process: #{x}"
-
end
-
end
-
end
-
end
-
end
-
1
module MultiJson
-
1
module Adapters
-
1
module JsonCommon
-
-
1
def load(string, options={})
-
42
string = string.read if string.respond_to?(:read)
-
42
::JSON.parse(string, :symbolize_names => options[:symbolize_keys])
-
end
-
-
1
def dump(object, options={})
-
object.to_json(process_options(options))
-
end
-
-
1
protected
-
-
1
def process_options(options={})
-
return options if options.empty?
-
opts = {}
-
opts.merge!(JSON::PRETTY_STATE_PROTOTYPE.to_h) if options.delete(:pretty)
-
opts.merge!(options)
-
end
-
-
end
-
end
-
end
-
1
require 'json' unless defined?(::JSON)
-
1
require 'multi_json/adapters/json_common'
-
-
1
module MultiJson
-
1
module Adapters
-
# Use the JSON gem to dump/load.
-
1
class JsonGem
-
1
ParseError = ::JSON::ParserError
-
1
extend JsonCommon
-
end
-
end
-
end
-
1
require 'multi_json/vendor/okjson'
-
-
1
module MultiJson
-
1
module Adapters
-
1
class OkJson
-
1
ParseError = ::MultiJson::OkJson::Error
-
-
1
def self.load(string, options={}) #:nodoc:
-
39
string = string.read if string.respond_to?(:read)
-
39
result = ::MultiJson::OkJson.decode(string)
-
39
options[:symbolize_keys] ? symbolize_keys(result) : result
-
end
-
-
1
def self.dump(object, options={}) #:nodoc:
-
::MultiJson::OkJson.valenc(stringify_keys(object))
-
end
-
-
1
def self.symbolize_keys(object) #:nodoc:
-
modify_keys(object) do |key|
-
key.is_a?(String) ? key.to_sym : key
-
end
-
end
-
-
1
def self.stringify_keys(object) #:nodoc:
-
modify_keys(object) do |key|
-
key.is_a?(Symbol) ? key.to_s : key
-
end
-
end
-
-
1
def self.modify_keys(object, &modifier) #:nodoc:
-
case object
-
when Array
-
object.map do |value|
-
modify_keys(value, &modifier)
-
end
-
when Hash
-
object.inject({}) do |result, (key, value)|
-
new_key = modifier.call(key)
-
new_value = modify_keys(value, &modifier)
-
result.merge! new_key => new_value
-
end
-
else
-
object
-
end
-
end
-
end
-
end
-
end
-
# encoding: UTF-8
-
#
-
# Copyright 2011, 2012 Keith Rarick
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in
-
# all copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
-
# See https://github.com/kr/okjson for updates.
-
-
1
require 'stringio'
-
-
# Some parts adapted from
-
# http://golang.org/src/pkg/json/decode.go and
-
# http://golang.org/src/pkg/utf8/utf8.go
-
1
module MultiJson
-
1
module OkJson
-
1
extend self
-
-
-
# Decodes a json document in string s and
-
# returns the corresponding ruby value.
-
# String s must be valid UTF-8. If you have
-
# a string in some other encoding, convert
-
# it first.
-
#
-
# String values in the resulting structure
-
# will be UTF-8.
-
1
def decode(s)
-
39
ts = lex(s)
-
39
v, ts = textparse(ts)
-
39
if ts.length > 0
-
raise Error, 'trailing garbage'
-
end
-
39
v
-
end
-
-
-
# Parses a "json text" in the sense of RFC 4627.
-
# Returns the parsed value and any trailing tokens.
-
# Note: this is almost the same as valparse,
-
# except that it does not accept atomic values.
-
1
def textparse(ts)
-
39
if ts.length < 0
-
raise Error, 'empty'
-
end
-
-
39
typ, _, val = ts[0]
-
39
case typ
-
34
when '{' then objparse(ts)
-
5
when '[' then arrparse(ts)
-
else
-
raise Error, "unexpected #{val.inspect}"
-
end
-
end
-
-
-
# Parses a "value" in the sense of RFC 4627.
-
# Returns the parsed value and any trailing tokens.
-
1
def valparse(ts)
-
63
if ts.length < 0
-
raise Error, 'empty'
-
end
-
-
63
typ, _, val = ts[0]
-
63
case typ
-
7
when '{' then objparse(ts)
-
3
when '[' then arrparse(ts)
-
53
when :val,:str then [val, ts[1..-1]]
-
else
-
raise Error, "unexpected #{val.inspect}"
-
end
-
end
-
-
-
# Parses an "object" in the sense of RFC 4627.
-
# Returns the parsed value and any trailing tokens.
-
1
def objparse(ts)
-
41
ts = eat('{', ts)
-
41
obj = {}
-
-
41
if ts[0][0] == '}'
-
1
return obj, ts[1..-1]
-
end
-
-
40
k, v, ts = pairparse(ts)
-
40
obj[k] = v
-
-
40
if ts[0][0] == '}'
-
32
return obj, ts[1..-1]
-
end
-
-
8
loop do
-
8
ts = eat(',', ts)
-
-
8
k, v, ts = pairparse(ts)
-
8
obj[k] = v
-
-
8
if ts[0][0] == '}'
-
8
return obj, ts[1..-1]
-
end
-
end
-
end
-
-
-
# Parses a "member" in the sense of RFC 4627.
-
# Returns the parsed values and any trailing tokens.
-
1
def pairparse(ts)
-
48
(typ, _, k), ts = ts[0], ts[1..-1]
-
48
if typ != :str
-
raise Error, "unexpected #{k.inspect}"
-
end
-
48
ts = eat(':', ts)
-
48
v, ts = valparse(ts)
-
48
[k, v, ts]
-
end
-
-
-
# Parses an "array" in the sense of RFC 4627.
-
# Returns the parsed value and any trailing tokens.
-
1
def arrparse(ts)
-
8
ts = eat('[', ts)
-
8
arr = []
-
-
8
if ts[0][0] == ']'
-
1
return arr, ts[1..-1]
-
end
-
-
7
v, ts = valparse(ts)
-
7
arr << v
-
-
7
if ts[0][0] == ']'
-
1
return arr, ts[1..-1]
-
end
-
-
6
loop do
-
8
ts = eat(',', ts)
-
-
8
v, ts = valparse(ts)
-
8
arr << v
-
-
8
if ts[0][0] == ']'
-
6
return arr, ts[1..-1]
-
end
-
end
-
end
-
-
-
1
def eat(typ, ts)
-
113
if ts[0][0] != typ
-
raise Error, "expected #{typ} (got #{ts[0].inspect})"
-
end
-
113
ts[1..-1]
-
end
-
-
-
# Scans s and returns a list of json tokens,
-
# excluding white space (as defined in RFC 4627).
-
1
def lex(s)
-
39
ts = []
-
39
while s.length > 0
-
294
typ, lexeme, val = tok(s)
-
294
if typ == nil
-
raise Error, "invalid character at #{s[0,10].inspect}"
-
end
-
294
if typ != :space
-
263
ts << [typ, lexeme, val]
-
end
-
294
s = s[lexeme.length..-1]
-
end
-
39
ts
-
end
-
-
-
# Scans the first token in s and
-
# returns a 3-element list, or nil
-
# if s does not begin with a valid token.
-
#
-
# The first list element is one of
-
# '{', '}', ':', ',', '[', ']',
-
# :val, :str, and :space.
-
#
-
# The second element is the lexeme.
-
#
-
# The third element is the value of the
-
# token for :val and :str, otherwise
-
# it is the lexeme.
-
1
def tok(s)
-
294
case s[0]
-
41
when ?{ then ['{', s[0,1], s[0,1]]
-
41
when ?} then ['}', s[0,1], s[0,1]]
-
48
when ?: then [':', s[0,1], s[0,1]]
-
16
when ?, then [',', s[0,1], s[0,1]]
-
8
when ?[ then ['[', s[0,1], s[0,1]]
-
8
when ?] then [']', s[0,1], s[0,1]]
-
1
when ?n then nulltok(s)
-
1
when ?t then truetok(s)
-
1
when ?f then falsetok(s)
-
94
when ?" then strtok(s)
-
31
when Spc then [:space, s[0,1], s[0,1]]
-
when ?\t then [:space, s[0,1], s[0,1]]
-
when ?\n then [:space, s[0,1], s[0,1]]
-
when ?\r then [:space, s[0,1], s[0,1]]
-
4
else numtok(s)
-
end
-
end
-
-
-
2
def nulltok(s); s[0,4] == 'null' ? [:val, 'null', nil] : [] end
-
2
def truetok(s); s[0,4] == 'true' ? [:val, 'true', true] : [] end
-
2
def falsetok(s); s[0,5] == 'false' ? [:val, 'false', false] : [] end
-
-
-
1
def numtok(s)
-
4
m = /-?([1-9][0-9]+|[0-9])([.][0-9]+)?([eE][+-]?[0-9]+)?/.match(s)
-
4
if m && m.begin(0) == 0
-
4
if m[3] && !m[2]
-
[:val, m[0], Integer(m[1])*(10**Integer(m[3][1..-1]))]
-
4
elsif m[2]
-
[:val, m[0], Float(m[0])]
-
else
-
4
[:val, m[0], Integer(m[0])]
-
end
-
else
-
[]
-
end
-
end
-
-
-
1
def strtok(s)
-
94
m = /"([^"\\]|\\["\/\\bfnrt]|\\u[0-9a-fA-F]{4})*"/.match(s)
-
94
if ! m
-
raise Error, "invalid string literal at #{abbrev(s)}"
-
end
-
94
[:str, m[0], unquote(m[0])]
-
end
-
-
-
1
def abbrev(s)
-
t = s[0,10]
-
p = t['`']
-
t = t[0,p] if p
-
t = t + '...' if t.length < s.length
-
'`' + t + '`'
-
end
-
-
-
# Converts a quoted json string literal q into a UTF-8-encoded string.
-
# The rules are different than for Ruby, so we cannot use eval.
-
# Unquote will raise an error if q contains control characters.
-
1
def unquote(q)
-
94
q = q[1...-1]
-
94
a = q.dup # allocate a big enough string
-
94
rubydoesenc = false
-
# In ruby >= 1.9, a[w] is a codepoint, not a byte.
-
94
if a.class.method_defined?(:force_encoding)
-
94
a.force_encoding('UTF-8')
-
94
rubydoesenc = true
-
end
-
94
r, w = 0, 0
-
94
while r < q.length
-
632
c = q[r]
-
632
case true
-
when c == ?\\
-
36
r += 1
-
36
if r >= q.length
-
raise Error, "string literal ends with a \"\\\": \"#{q}\""
-
end
-
-
36
case q[r]
-
when ?",?\\,?/,?'
-
20
a[w] = q[r]
-
20
r += 1
-
20
w += 1
-
when ?b,?f,?n,?r,?t
-
1
a[w] = Unesc[q[r]]
-
1
r += 1
-
1
w += 1
-
when ?u
-
15
r += 1
-
15
uchar = begin
-
15
hexdec4(q[r,4])
-
rescue RuntimeError => e
-
raise Error, "invalid escape sequence \\u#{q[r,4]}: #{e}"
-
end
-
15
r += 4
-
15
if surrogate? uchar
-
if q.length >= r+6
-
uchar1 = hexdec4(q[r+2,4])
-
uchar = subst(uchar, uchar1)
-
if uchar != Ucharerr
-
# A valid pair; consume.
-
r += 6
-
end
-
end
-
end
-
15
if rubydoesenc
-
15
a[w] = '' << uchar
-
15
w += 1
-
else
-
w += ucharenc(a, w, uchar)
-
end
-
else
-
raise Error, "invalid escape char #{q[r]} in \"#{q}\""
-
end
-
when c == ?", c < Spc
-
raise Error, "invalid character in string literal \"#{q}\""
-
else
-
# Copy anything else byte-for-byte.
-
# Valid UTF-8 will remain valid UTF-8.
-
# Invalid UTF-8 will remain invalid UTF-8.
-
# In ruby >= 1.9, c is a codepoint, not a byte,
-
# in which case this is still what we want.
-
596
a[w] = c
-
596
r += 1
-
596
w += 1
-
end
-
end
-
94
a[0,w]
-
end
-
-
-
# Encodes unicode character u as UTF-8
-
# bytes in string a at position i.
-
# Returns the number of bytes written.
-
1
def ucharenc(a, i, u)
-
case true
-
when u <= Uchar1max
-
a[i] = (u & 0xff).chr
-
1
-
when u <= Uchar2max
-
a[i+0] = (Utag2 | ((u>>6)&0xff)).chr
-
a[i+1] = (Utagx | (u&Umaskx)).chr
-
2
-
when u <= Uchar3max
-
a[i+0] = (Utag3 | ((u>>12)&0xff)).chr
-
a[i+1] = (Utagx | ((u>>6)&Umaskx)).chr
-
a[i+2] = (Utagx | (u&Umaskx)).chr
-
3
-
else
-
a[i+0] = (Utag4 | ((u>>18)&0xff)).chr
-
a[i+1] = (Utagx | ((u>>12)&Umaskx)).chr
-
a[i+2] = (Utagx | ((u>>6)&Umaskx)).chr
-
a[i+3] = (Utagx | (u&Umaskx)).chr
-
4
-
end
-
end
-
-
-
1
def hexdec4(s)
-
15
if s.length != 4
-
raise Error, 'short'
-
end
-
15
(nibble(s[0])<<12) | (nibble(s[1])<<8) | (nibble(s[2])<<4) | nibble(s[3])
-
end
-
-
-
1
def subst(u1, u2)
-
if Usurr1 <= u1 && u1 < Usurr2 && Usurr2 <= u2 && u2 < Usurr3
-
return ((u1-Usurr1)<<10) | (u2-Usurr2) + Usurrself
-
end
-
return Ucharerr
-
end
-
-
-
1
def surrogate?(u)
-
15
Usurr1 <= u && u < Usurr3
-
end
-
-
-
1
def nibble(c)
-
60
case true
-
48
when ?0 <= c && c <= ?9 then c.ord - ?0.ord
-
12
when ?a <= c && c <= ?z then c.ord - ?a.ord + 10
-
when ?A <= c && c <= ?Z then c.ord - ?A.ord + 10
-
else
-
raise Error, "invalid hex code #{c}"
-
end
-
end
-
-
-
# Encodes x into a json text. It may contain only
-
# Array, Hash, String, Numeric, true, false, nil.
-
# (Note, this list excludes Symbol.)
-
# X itself must be an Array or a Hash.
-
# No other value can be encoded, and an error will
-
# be raised if x contains any other value, such as
-
# Nan, Infinity, Symbol, and Proc, or if a Hash key
-
# is not a String.
-
# Strings contained in x must be valid UTF-8.
-
1
def encode(x)
-
case x
-
when Hash then objenc(x)
-
when Array then arrenc(x)
-
else
-
raise Error, 'root value must be an Array or a Hash'
-
end
-
end
-
-
-
1
def valenc(x)
-
case x
-
when Hash then objenc(x)
-
when Array then arrenc(x)
-
when String then strenc(x)
-
when Numeric then numenc(x)
-
when true then "true"
-
when false then "false"
-
when nil then "null"
-
else
-
if x.respond_to?(:to_json)
-
x.to_json
-
else
-
raise Error, "cannot encode #{x.class}: #{x.inspect}"
-
end
-
end
-
end
-
-
-
1
def objenc(x)
-
'{' + x.map{|k,v| keyenc(k) + ':' + valenc(v)}.join(',') + '}'
-
end
-
-
-
1
def arrenc(a)
-
'[' + a.map{|x| valenc(x)}.join(',') + ']'
-
end
-
-
-
1
def keyenc(k)
-
case k
-
when String then strenc(k)
-
else
-
raise Error, "Hash key is not a string: #{k.inspect}"
-
end
-
end
-
-
-
1
def strenc(s)
-
t = StringIO.new
-
t.putc(?")
-
r = 0
-
-
# In ruby >= 1.9, s[r] is a codepoint, not a byte.
-
rubydoesenc = s.class.method_defined?(:encoding)
-
-
while r < s.length
-
case s[r]
-
when ?" then t.print('\\"')
-
when ?\\ then t.print('\\\\')
-
when ?\b then t.print('\\b')
-
when ?\f then t.print('\\f')
-
when ?\n then t.print('\\n')
-
when ?\r then t.print('\\r')
-
when ?\t then t.print('\\t')
-
else
-
c = s[r]
-
case true
-
when rubydoesenc
-
begin
-
c.ord # will raise an error if c is invalid UTF-8
-
t.write(c)
-
rescue
-
t.write(Ustrerr)
-
end
-
when Spc <= c && c <= ?~
-
t.putc(c)
-
else
-
n = ucharcopy(t, s, r) # ensure valid UTF-8 output
-
r += n - 1 # r is incremented below
-
end
-
end
-
r += 1
-
end
-
t.putc(?")
-
t.string
-
end
-
-
-
1
def numenc(x)
-
if ((x.nan? || x.infinite?) rescue false)
-
raise Error, "Numeric cannot be represented: #{x}"
-
end
-
"#{x}"
-
end
-
-
-
# Copies the valid UTF-8 bytes of a single character
-
# from string s at position i to I/O object t, and
-
# returns the number of bytes copied.
-
# If no valid UTF-8 char exists at position i,
-
# ucharcopy writes Ustrerr and returns 1.
-
1
def ucharcopy(t, s, i)
-
n = s.length - i
-
raise Utf8Error if n < 1
-
-
c0 = s[i].ord
-
-
# 1-byte, 7-bit sequence?
-
if c0 < Utagx
-
t.putc(c0)
-
return 1
-
end
-
-
raise Utf8Error if c0 < Utag2 # unexpected continuation byte?
-
-
raise Utf8Error if n < 2 # need continuation byte
-
c1 = s[i+1].ord
-
raise Utf8Error if c1 < Utagx || Utag2 <= c1
-
-
# 2-byte, 11-bit sequence?
-
if c0 < Utag3
-
raise Utf8Error if ((c0&Umask2)<<6 | (c1&Umaskx)) <= Uchar1max
-
t.putc(c0)
-
t.putc(c1)
-
return 2
-
end
-
-
# need second continuation byte
-
raise Utf8Error if n < 3
-
-
c2 = s[i+2].ord
-
raise Utf8Error if c2 < Utagx || Utag2 <= c2
-
-
# 3-byte, 16-bit sequence?
-
if c0 < Utag4
-
u = (c0&Umask3)<<12 | (c1&Umaskx)<<6 | (c2&Umaskx)
-
raise Utf8Error if u <= Uchar2max
-
t.putc(c0)
-
t.putc(c1)
-
t.putc(c2)
-
return 3
-
end
-
-
# need third continuation byte
-
raise Utf8Error if n < 4
-
c3 = s[i+3].ord
-
raise Utf8Error if c3 < Utagx || Utag2 <= c3
-
-
# 4-byte, 21-bit sequence?
-
if c0 < Utag5
-
u = (c0&Umask4)<<18 | (c1&Umaskx)<<12 | (c2&Umaskx)<<6 | (c3&Umaskx)
-
raise Utf8Error if u <= Uchar3max
-
t.putc(c0)
-
t.putc(c1)
-
t.putc(c2)
-
t.putc(c3)
-
return 4
-
end
-
-
raise Utf8Error
-
rescue Utf8Error
-
t.write(Ustrerr)
-
return 1
-
end
-
-
-
1
class Utf8Error < ::StandardError
-
end
-
-
-
1
class Error < ::StandardError
-
end
-
-
-
1
Utagx = 0x80 # 1000 0000
-
1
Utag2 = 0xc0 # 1100 0000
-
1
Utag3 = 0xe0 # 1110 0000
-
1
Utag4 = 0xf0 # 1111 0000
-
1
Utag5 = 0xF8 # 1111 1000
-
1
Umaskx = 0x3f # 0011 1111
-
1
Umask2 = 0x1f # 0001 1111
-
1
Umask3 = 0x0f # 0000 1111
-
1
Umask4 = 0x07 # 0000 0111
-
1
Uchar1max = (1<<7) - 1
-
1
Uchar2max = (1<<11) - 1
-
1
Uchar3max = (1<<16) - 1
-
1
Ucharerr = 0xFFFD # unicode "replacement char"
-
1
Ustrerr = "\xef\xbf\xbd" # unicode "replacement char"
-
1
Usurrself = 0x10000
-
1
Usurr1 = 0xd800
-
1
Usurr2 = 0xdc00
-
1
Usurr3 = 0xe000
-
-
1
Spc = ' '[0]
-
1
Unesc = {?b=>?\b, ?f=>?\f, ?n=>?\n, ?r=>?\r, ?t=>?\t}
-
end
-
end
-
# -*- coding: utf-8 -*-
-
# Modify the PATH on windows so that the external DLLs will get loaded.
-
-
1
require 'rbconfig'
-
ENV['PATH'] = [File.expand_path(
-
File.join(File.dirname(__FILE__), "..", "ext", "nokogiri")
-
1
), ENV['PATH']].compact.join(';') if RbConfig::CONFIG['host_os'] =~ /(mswin|mingw)/i
-
-
1
if defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby"
-
# The line below caused a problem on non-GAE rack environment.
-
# unless defined?(JRuby::Rack::VERSION) || defined?(AppEngine::ApiProxy)
-
#
-
# However, simply cutting defined?(JRuby::Rack::VERSION) off resulted in
-
# an unable-to-load-nokogiri problem. Thus, now, Nokogiri checks the presense
-
# of appengine-rack.jar in $LOAD_PATH. If Nokogiri is on GAE, Nokogiri
-
# should skip loading xml jars. This is because those are in WEB-INF/lib and
-
# already set in the classpath.
-
unless $LOAD_PATH.to_s.include?("appengine-rack")
-
require 'isorelax.jar'
-
require 'jing.jar'
-
require 'nekohtml.jar'
-
require 'nekodtd.jar'
-
require 'xercesImpl.jar'
-
end
-
end
-
-
1
require 'nokogiri/nokogiri'
-
1
require 'nokogiri/version'
-
1
require 'nokogiri/syntax_error'
-
1
require 'nokogiri/xml'
-
1
require 'nokogiri/xslt'
-
1
require 'nokogiri/html'
-
1
require 'nokogiri/decorators/slop'
-
1
require 'nokogiri/css'
-
1
require 'nokogiri/html/builder'
-
-
# Nokogiri parses and searches XML/HTML very quickly, and also has
-
# correctly implemented CSS3 selector support as well as XPath support.
-
#
-
# Parsing a document returns either a Nokogiri::XML::Document, or a
-
# Nokogiri::HTML::Document depending on the kind of document you parse.
-
#
-
# Here is an example:
-
#
-
# require 'nokogiri'
-
# require 'open-uri'
-
#
-
# # Get a Nokogiri::HTML:Document for the page we’re interested in...
-
#
-
# doc = Nokogiri::HTML(open('http://www.google.com/search?q=tenderlove'))
-
#
-
# # Do funky things with it using Nokogiri::XML::Node methods...
-
#
-
# ####
-
# # Search for nodes by css
-
# doc.css('h3.r a.l').each do |link|
-
# puts link.content
-
# end
-
#
-
# See Nokogiri::XML::Node#css for more information about CSS searching.
-
# See Nokogiri::XML::Node#xpath for more information about XPath searching.
-
1
module Nokogiri
-
1
class << self
-
###
-
# Parse an HTML or XML document. +string+ contains the document.
-
1
def parse string, url = nil, encoding = nil, options = nil
-
doc =
-
if string.respond_to?(:read) ||
-
string =~ /^\s*<[^Hh>]*html/i # Probably html
-
Nokogiri.HTML(
-
string,
-
url,
-
encoding, options || XML::ParseOptions::DEFAULT_HTML
-
)
-
else
-
Nokogiri.XML(string, url, encoding,
-
options || XML::ParseOptions::DEFAULT_XML)
-
end
-
yield doc if block_given?
-
doc
-
end
-
-
###
-
# Create a new Nokogiri::XML::DocumentFragment
-
1
def make input = nil, opts = {}, &blk
-
if input
-
Nokogiri::HTML.fragment(input).children.first
-
else
-
Nokogiri(&blk)
-
end
-
end
-
-
###
-
# Parse a document and add the Slop decorator. The Slop decorator
-
# implements method_missing such that methods may be used instead of CSS
-
# or XPath. For example:
-
#
-
# doc = Nokogiri::Slop(<<-eohtml)
-
# <html>
-
# <body>
-
# <p>first</p>
-
# <p>second</p>
-
# </body>
-
# </html>
-
# eohtml
-
# assert_equal('second', doc.html.body.p[1].text)
-
#
-
1
def Slop(*args, &block)
-
Nokogiri(*args, &block).slop!
-
end
-
end
-
end
-
-
###
-
# Parser a document contained in +args+. Nokogiri will try to guess what
-
# type of document you are attempting to parse. For more information, see
-
# Nokogiri.parse
-
#
-
# To specify the type of document, use Nokogiri.XML or Nokogiri.HTML.
-
1
def Nokogiri(*args, &block)
-
if block_given?
-
builder = Nokogiri::HTML::Builder.new(&block)
-
return builder.doc.root
-
else
-
Nokogiri.parse(*args)
-
end
-
end
-
1
require 'nokogiri/css/node'
-
1
require 'nokogiri/css/xpath_visitor'
-
1
x = $-w
-
1
$-w = false
-
1
require 'nokogiri/css/parser'
-
1
$-w = x
-
-
1
require 'nokogiri/css/tokenizer'
-
1
require 'nokogiri/css/syntax_error'
-
-
1
module Nokogiri
-
1
module CSS
-
1
class << self
-
###
-
# Parse this CSS selector in +selector+. Returns an AST.
-
1
def parse selector
-
Parser.new.parse selector
-
end
-
-
###
-
# Get the XPath for +selector+.
-
1
def xpath_for selector, options={}
-
Parser.new(options[:ns] || {}).xpath_for selector, options
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module CSS
-
1
class Node
-
1
ALLOW_COMBINATOR_ON_SELF = [:DIRECT_ADJACENT_SELECTOR, :FOLLOWING_SELECTOR, :CHILD_SELECTOR]
-
-
# Get the type of this node
-
1
attr_accessor :type
-
# Get the value of this node
-
1
attr_accessor :value
-
-
# Create a new Node with +type+ and +value+
-
1
def initialize type, value
-
@type = type
-
@value = value
-
end
-
-
# Accept +visitor+
-
1
def accept visitor
-
visitor.send(:"visit_#{type.to_s.downcase}", self)
-
end
-
-
###
-
# Convert this CSS node to xpath with +prefix+ using +visitor+
-
1
def to_xpath prefix = '//', visitor = XPathVisitor.new
-
self.preprocess!
-
prefix = '.' if ALLOW_COMBINATOR_ON_SELF.include?(type) && value.first.nil?
-
prefix + visitor.accept(self)
-
end
-
-
# Preprocess this node tree
-
1
def preprocess!
-
### Deal with nth-child
-
matches = find_by_type(
-
[:CONDITIONAL_SELECTOR,
-
[:ELEMENT_NAME],
-
[:PSEUDO_CLASS,
-
[:FUNCTION]
-
]
-
]
-
)
-
matches.each do |match|
-
if match.value[1].value[0].value[0] =~ /^nth-(last-)?child/
-
tag_name = match.value[0].value.first
-
match.value[0].value = ['*']
-
match.value[1] = Node.new(:COMBINATOR, [
-
match.value[1].value[0],
-
Node.new(:FUNCTION, ['self(', tag_name])
-
])
-
end
-
end
-
-
### Deal with first-child, last-child
-
matches = find_by_type(
-
[:CONDITIONAL_SELECTOR,
-
[:ELEMENT_NAME], [:PSEUDO_CLASS]
-
])
-
matches.each do |match|
-
if ['first-child', 'last-child'].include?(match.value[1].value.first)
-
which = match.value[1].value.first.gsub(/-\w*$/, '')
-
tag_name = match.value[0].value.first
-
match.value[0].value = ['*']
-
match.value[1] = Node.new(:COMBINATOR, [
-
Node.new(:FUNCTION, ["#{which}("]),
-
Node.new(:FUNCTION, ['self(', tag_name])
-
])
-
elsif 'only-child' == match.value[1].value.first
-
tag_name = match.value[0].value.first
-
match.value[0].value = ['*']
-
match.value[1] = Node.new(:COMBINATOR, [
-
Node.new(:FUNCTION, ["#{match.value[1].value.first}("]),
-
Node.new(:FUNCTION, ['self(', tag_name])
-
])
-
end
-
end
-
-
self
-
end
-
-
# Find a node by type using +types+
-
1
def find_by_type types
-
matches = []
-
matches << self if to_type == types
-
@value.each do |v|
-
matches += v.find_by_type(types) if v.respond_to?(:find_by_type)
-
end
-
matches
-
end
-
-
# Convert to_type
-
1
def to_type
-
[@type] + @value.map { |n|
-
n.to_type if n.respond_to?(:to_type)
-
}.compact
-
end
-
-
# Convert to array
-
1
def to_a
-
[@type] + @value.map { |n| n.respond_to?(:to_a) ? n.to_a : [n] }
-
end
-
end
-
end
-
end
-
#
-
# DO NOT MODIFY!!!!
-
# This file is automatically generated by Racc 1.4.8
-
# from Racc grammer file "".
-
#
-
-
1
require 'racc/parser.rb'
-
-
-
1
require 'nokogiri/css/parser_extras'
-
1
module Nokogiri
-
1
module CSS
-
1
class Parser < Racc::Parser
-
##### State transition tables begin ###
-
-
1
racc_action_table = [
-
21, 4, 5, 7, 29, 4, 5, 7, 30, 19,
-
-26, 6, 21, 9, 8, 6, 29, 9, 8, 22,
-
31, 19, 20, 21, 23, 15, 17, 29, 24, 83,
-
31, 22, 19, 84, 20, 21, 23, 15, 17, 29,
-
24, 92, 22, 85, 19, 20, 21, 23, 15, 17,
-
20, 24, 82, 90, 22, 59, 24, 20, 89, 23,
-
15, 17, 21, 24, 88, 22, 29, 4, 5, 7,
-
23, 19, 71, 29, 91, 29, 86, 6, 19, 9,
-
8, 22, 29, 29, 20, 89, 23, 15, 17, 35,
-
24, 20, 29, 20, 15, 17, 15, 24, 35, 24,
-
20, 20, 29, 15, 15, 93, 24, 24, 21, 64,
-
20, 95, 29, 15, 97, 96, 24, 43, -26, 46,
-
20, 52, 53, 15, 51, 98, 24, 22, 79, 80,
-
20, 99, 23, 15, 48, 42, 24, 79, 80, 75,
-
76, 77, 101, 78, 87, 86, 41, 74, 75, 76,
-
77, 35, 78, 104, 52, 56, 74, 55, 52, 56,
-
105, 55, 52, 56, nil, 55, 52, 56, nil, 55 ]
-
-
1
racc_action_check = [
-
0, 14, 14, 14, 0, 0, 0, 0, 1, 0,
-
43, 14, 40, 14, 14, 0, 40, 0, 0, 0,
-
1, 40, 0, 31, 0, 0, 0, 31, 0, 47,
-
57, 40, 31, 49, 40, 13, 40, 40, 40, 13,
-
40, 57, 31, 50, 13, 31, 24, 31, 31, 31,
-
11, 31, 46, 53, 13, 24, 11, 13, 53, 13,
-
13, 13, 23, 13, 52, 24, 23, 23, 23, 23,
-
24, 23, 42, 35, 54, 28, 55, 23, 35, 23,
-
23, 23, 27, 10, 23, 56, 23, 23, 23, 33,
-
23, 35, 26, 28, 35, 35, 28, 35, 10, 28,
-
27, 10, 25, 27, 10, 67, 27, 10, 20, 30,
-
26, 72, 68, 26, 73, 73, 26, 20, 19, 20,
-
25, 21, 21, 25, 21, 81, 25, 20, 45, 45,
-
68, 83, 20, 68, 21, 18, 68, 44, 44, 45,
-
45, 45, 87, 45, 51, 51, 15, 45, 44, 44,
-
44, 12, 44, 90, 89, 89, 44, 89, 86, 86,
-
101, 86, 88, 88, nil, 88, 22, 22, nil, 22 ]
-
-
1
racc_action_pointer = [
-
-2, 8, nil, nil, nil, nil, nil, nil, nil, nil,
-
77, 26, 130, 33, -6, 135, nil, nil, 106, 89,
-
106, 111, 156, 60, 44, 96, 86, 76, 69, nil,
-
109, 21, nil, 68, nil, 67, nil, nil, nil, nil,
-
10, nil, 61, -19, 134, 125, 27, 0, nil, 10,
-
20, 133, 52, 46, 51, 64, 73, 18, nil, nil,
-
nil, nil, nil, nil, nil, nil, nil, 82, 106, nil,
-
nil, nil, 86, 104, nil, nil, nil, nil, nil, nil,
-
nil, 100, nil, 120, nil, nil, 148, 135, 152, 144,
-
140, nil, nil, nil, nil, nil, nil, nil, nil, nil,
-
nil, 147, nil, nil, nil, nil ]
-
-
1
racc_action_default = [
-
-27, -74, -2, -3, -4, -5, -6, -7, -8, -9,
-
-50, -13, -17, -27, -20, -74, -22, -23, -74, -25,
-
-27, -74, -74, -27, -74, -55, -56, -57, -58, -59,
-
-74, -27, -10, -49, -12, -27, -14, -15, -16, -18,
-
-27, -21, -74, -32, -62, -62, -74, -74, -33, -74,
-
-74, -41, -42, -43, -74, -41, -43, -74, -47, -48,
-
-51, -52, -53, -54, 106, -1, -11, -74, -71, -73,
-
-19, -24, -74, -74, -63, -64, -65, -66, -67, -68,
-
-69, -74, -30, -74, -34, -35, -74, -46, -74, -74,
-
-74, -36, -37, -70, -72, -28, -60, -61, -29, -31,
-
-38, -74, -39, -40, -45, -44 ]
-
-
1
racc_goto_table = [
-
49, 54, 33, 39, 36, 1, 34, 45, 38, 72,
-
81, 58, 32, 37, 47, 44, 68, 60, 61, 62,
-
63, 65, 40, 50, 67, nil, nil, 69, 57, 66,
-
70, nil, nil, nil, nil, nil, nil, nil, nil, nil,
-
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
-
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
-
94, nil, nil, nil, nil, 100, nil, 102, 103 ]
-
-
1
racc_goto_check = [
-
18, 18, 8, 2, 11, 1, 9, 10, 9, 17,
-
17, 10, 7, 12, 15, 16, 6, 8, 8, 8,
-
8, 2, 4, 19, 22, nil, nil, 8, 1, 9,
-
2, nil, nil, nil, nil, nil, nil, nil, nil, nil,
-
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
-
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
-
8, nil, nil, nil, nil, 18, nil, 18, 18 ]
-
-
1
racc_goto_pointer = [
-
nil, 5, -10, nil, 8, nil, -19, 2, -8, -4,
-
-13, -7, 2, nil, nil, -6, -5, -35, -21, 2,
-
nil, nil, -11 ]
-
-
1
racc_goto_default = [
-
nil, nil, 3, 2, 13, 14, 10, nil, 12, nil,
-
11, 28, 27, 26, 16, 18, nil, nil, nil, nil,
-
25, 73, nil ]
-
-
1
racc_reduce_table = [
-
0, 0, :racc_error,
-
3, 32, :_reduce_1,
-
1, 32, :_reduce_2,
-
1, 32, :_reduce_3,
-
1, 35, :_reduce_4,
-
1, 35, :_reduce_5,
-
1, 35, :_reduce_6,
-
1, 35, :_reduce_7,
-
1, 35, :_reduce_8,
-
1, 35, :_reduce_9,
-
2, 36, :_reduce_10,
-
3, 36, :_reduce_11,
-
2, 36, :_reduce_12,
-
1, 36, :_reduce_none,
-
2, 36, :_reduce_14,
-
2, 36, :_reduce_15,
-
2, 36, :_reduce_16,
-
1, 36, :_reduce_17,
-
2, 34, :_reduce_18,
-
3, 33, :_reduce_19,
-
1, 33, :_reduce_none,
-
2, 44, :_reduce_21,
-
1, 37, :_reduce_none,
-
1, 37, :_reduce_23,
-
3, 45, :_reduce_24,
-
1, 45, :_reduce_25,
-
1, 46, :_reduce_26,
-
0, 46, :_reduce_none,
-
4, 43, :_reduce_28,
-
4, 43, :_reduce_29,
-
3, 43, :_reduce_30,
-
3, 47, :_reduce_31,
-
1, 47, :_reduce_32,
-
2, 41, :_reduce_33,
-
3, 41, :_reduce_34,
-
3, 41, :_reduce_35,
-
3, 41, :_reduce_36,
-
3, 41, :_reduce_37,
-
3, 49, :_reduce_38,
-
3, 49, :_reduce_39,
-
3, 49, :_reduce_40,
-
1, 49, :_reduce_none,
-
1, 49, :_reduce_none,
-
1, 49, :_reduce_43,
-
4, 50, :_reduce_44,
-
3, 50, :_reduce_45,
-
2, 50, :_reduce_46,
-
2, 42, :_reduce_47,
-
2, 42, :_reduce_48,
-
1, 38, :_reduce_none,
-
0, 38, :_reduce_none,
-
2, 39, :_reduce_51,
-
2, 39, :_reduce_52,
-
2, 39, :_reduce_53,
-
2, 39, :_reduce_54,
-
1, 39, :_reduce_none,
-
1, 39, :_reduce_none,
-
1, 39, :_reduce_none,
-
1, 39, :_reduce_none,
-
1, 51, :_reduce_59,
-
2, 48, :_reduce_60,
-
2, 48, :_reduce_61,
-
0, 48, :_reduce_none,
-
1, 52, :_reduce_63,
-
1, 52, :_reduce_64,
-
1, 52, :_reduce_65,
-
1, 52, :_reduce_66,
-
1, 52, :_reduce_67,
-
1, 52, :_reduce_68,
-
1, 52, :_reduce_69,
-
3, 40, :_reduce_70,
-
1, 53, :_reduce_none,
-
2, 53, :_reduce_none,
-
1, 53, :_reduce_none ]
-
-
1
racc_reduce_n = 74
-
-
1
racc_shift_n = 106
-
-
1
racc_token_table = {
-
false => 0,
-
:error => 1,
-
:FUNCTION => 2,
-
:INCLUDES => 3,
-
:DASHMATCH => 4,
-
:LBRACE => 5,
-
:HASH => 6,
-
:PLUS => 7,
-
:GREATER => 8,
-
:S => 9,
-
:STRING => 10,
-
:IDENT => 11,
-
:COMMA => 12,
-
:NUMBER => 13,
-
:PREFIXMATCH => 14,
-
:SUFFIXMATCH => 15,
-
:SUBSTRINGMATCH => 16,
-
:TILDE => 17,
-
:NOT_EQUAL => 18,
-
:SLASH => 19,
-
:DOUBLESLASH => 20,
-
:NOT => 21,
-
:EQUAL => 22,
-
:RPAREN => 23,
-
:LSQUARE => 24,
-
:RSQUARE => 25,
-
:HAS => 26,
-
"." => 27,
-
"*" => 28,
-
"|" => 29,
-
":" => 30 }
-
-
1
racc_nt_base = 31
-
-
1
racc_use_result_var = true
-
-
1
Racc_arg = [
-
racc_action_table,
-
racc_action_check,
-
racc_action_default,
-
racc_action_pointer,
-
racc_goto_table,
-
racc_goto_check,
-
racc_goto_default,
-
racc_goto_pointer,
-
racc_nt_base,
-
racc_reduce_table,
-
racc_token_table,
-
racc_shift_n,
-
racc_reduce_n,
-
racc_use_result_var ]
-
-
1
Racc_token_to_s_table = [
-
"$end",
-
"error",
-
"FUNCTION",
-
"INCLUDES",
-
"DASHMATCH",
-
"LBRACE",
-
"HASH",
-
"PLUS",
-
"GREATER",
-
"S",
-
"STRING",
-
"IDENT",
-
"COMMA",
-
"NUMBER",
-
"PREFIXMATCH",
-
"SUFFIXMATCH",
-
"SUBSTRINGMATCH",
-
"TILDE",
-
"NOT_EQUAL",
-
"SLASH",
-
"DOUBLESLASH",
-
"NOT",
-
"EQUAL",
-
"RPAREN",
-
"LSQUARE",
-
"RSQUARE",
-
"HAS",
-
"\".\"",
-
"\"*\"",
-
"\"|\"",
-
"\":\"",
-
"$start",
-
"selector",
-
"simple_selector_1toN",
-
"prefixless_combinator_selector",
-
"combinator",
-
"simple_selector",
-
"element_name",
-
"hcap_0toN",
-
"hcap_1toN",
-
"negation",
-
"function",
-
"pseudo",
-
"attrib",
-
"class",
-
"namespaced_ident",
-
"namespace",
-
"attrib_name",
-
"attrib_val_0or1",
-
"expr",
-
"an_plus_b",
-
"attribute_id",
-
"eql_incl_dash",
-
"negation_arg" ]
-
-
1
Racc_debug_parser = false
-
-
##### State transition tables end #####
-
-
# reduce 0 omitted
-
-
1
def _reduce_1(val, _values, result)
-
result = [val.first, val.last].flatten
-
-
result
-
end
-
-
1
def _reduce_2(val, _values, result)
-
result = val.flatten
-
result
-
end
-
-
1
def _reduce_3(val, _values, result)
-
result = val.flatten
-
result
-
end
-
-
1
def _reduce_4(val, _values, result)
-
result = :DIRECT_ADJACENT_SELECTOR
-
result
-
end
-
-
1
def _reduce_5(val, _values, result)
-
result = :CHILD_SELECTOR
-
result
-
end
-
-
1
def _reduce_6(val, _values, result)
-
result = :FOLLOWING_SELECTOR
-
result
-
end
-
-
1
def _reduce_7(val, _values, result)
-
result = :DESCENDANT_SELECTOR
-
result
-
end
-
-
1
def _reduce_8(val, _values, result)
-
result = :DESCENDANT_SELECTOR
-
result
-
end
-
-
1
def _reduce_9(val, _values, result)
-
result = :CHILD_SELECTOR
-
result
-
end
-
-
1
def _reduce_10(val, _values, result)
-
result = if val[1].nil?
-
val.first
-
else
-
Node.new(:CONDITIONAL_SELECTOR, [val.first, val[1]])
-
end
-
-
result
-
end
-
-
1
def _reduce_11(val, _values, result)
-
result = Node.new(:CONDITIONAL_SELECTOR,
-
[
-
val.first,
-
Node.new(:COMBINATOR, [val[1], val.last])
-
]
-
)
-
-
result
-
end
-
-
1
def _reduce_12(val, _values, result)
-
result = Node.new(:CONDITIONAL_SELECTOR, val)
-
-
result
-
end
-
-
# reduce 13 omitted
-
-
1
def _reduce_14(val, _values, result)
-
result = Node.new(:CONDITIONAL_SELECTOR, val)
-
-
result
-
end
-
-
1
def _reduce_15(val, _values, result)
-
result = Node.new(:CONDITIONAL_SELECTOR, val)
-
-
result
-
end
-
-
1
def _reduce_16(val, _values, result)
-
result = Node.new(:CONDITIONAL_SELECTOR,
-
[
-
Node.new(:ELEMENT_NAME, ['*']),
-
Node.new(:COMBINATOR, val)
-
]
-
)
-
-
result
-
end
-
-
1
def _reduce_17(val, _values, result)
-
result = Node.new(:CONDITIONAL_SELECTOR,
-
[Node.new(:ELEMENT_NAME, ['*']), val.first]
-
)
-
-
result
-
end
-
-
1
def _reduce_18(val, _values, result)
-
result = Node.new(val.first, [nil, val.last])
-
-
result
-
end
-
-
1
def _reduce_19(val, _values, result)
-
result = Node.new(val[1], [val.first, val.last])
-
-
result
-
end
-
-
# reduce 20 omitted
-
-
1
def _reduce_21(val, _values, result)
-
result = Node.new(:CLASS_CONDITION, [val[1]])
-
result
-
end
-
-
# reduce 22 omitted
-
-
1
def _reduce_23(val, _values, result)
-
result = Node.new(:ELEMENT_NAME, val)
-
result
-
end
-
-
1
def _reduce_24(val, _values, result)
-
result = Node.new(:ELEMENT_NAME,
-
[[val.first, val.last].compact.join(':')]
-
)
-
-
result
-
end
-
-
1
def _reduce_25(val, _values, result)
-
name = @namespaces.key?('xmlns') ? "xmlns:#{val.first}" : val.first
-
result = Node.new(:ELEMENT_NAME, [name])
-
-
result
-
end
-
-
1
def _reduce_26(val, _values, result)
-
result = val[0]
-
result
-
end
-
-
# reduce 27 omitted
-
-
1
def _reduce_28(val, _values, result)
-
result = Node.new(:ATTRIBUTE_CONDITION,
-
[val[1]] + (val[2] || [])
-
)
-
-
result
-
end
-
-
1
def _reduce_29(val, _values, result)
-
result = Node.new(:ATTRIBUTE_CONDITION,
-
[val[1]] + (val[2] || [])
-
)
-
-
result
-
end
-
-
1
def _reduce_30(val, _values, result)
-
# Non standard, but hpricot supports it.
-
result = Node.new(:PSEUDO_CLASS,
-
[Node.new(:FUNCTION, ['nth-child(', val[1]])]
-
)
-
-
result
-
end
-
-
1
def _reduce_31(val, _values, result)
-
result = Node.new(:ELEMENT_NAME,
-
[[val.first, val.last].compact.join(':')]
-
)
-
-
result
-
end
-
-
1
def _reduce_32(val, _values, result)
-
# Default namespace is not applied to attributes.
-
# So we don't add prefix "xmlns:" as in namespaced_ident.
-
result = Node.new(:ELEMENT_NAME, [val.first])
-
-
result
-
end
-
-
1
def _reduce_33(val, _values, result)
-
result = Node.new(:FUNCTION, [val.first.strip])
-
-
result
-
end
-
-
1
def _reduce_34(val, _values, result)
-
result = Node.new(:FUNCTION, [val.first.strip, val[1]].flatten)
-
-
result
-
end
-
-
1
def _reduce_35(val, _values, result)
-
result = Node.new(:FUNCTION, [val.first.strip, val[1]].flatten)
-
-
result
-
end
-
-
1
def _reduce_36(val, _values, result)
-
result = Node.new(:FUNCTION, [val.first.strip, val[1]].flatten)
-
-
result
-
end
-
-
1
def _reduce_37(val, _values, result)
-
result = Node.new(:FUNCTION, [val.first.strip, val[1]].flatten)
-
-
result
-
end
-
-
1
def _reduce_38(val, _values, result)
-
result = [val.first, val.last]
-
result
-
end
-
-
1
def _reduce_39(val, _values, result)
-
result = [val.first, val.last]
-
result
-
end
-
-
1
def _reduce_40(val, _values, result)
-
result = [val.first, val.last]
-
result
-
end
-
-
# reduce 41 omitted
-
-
# reduce 42 omitted
-
-
1
def _reduce_43(val, _values, result)
-
if val[0] == 'even'
-
val = ["2","n","+","0"]
-
result = Node.new(:AN_PLUS_B, val)
-
elsif val[0] == 'odd'
-
val = ["2","n","+","1"]
-
result = Node.new(:AN_PLUS_B, val)
-
else
-
# This is not CSS standard. It allows us to support this:
-
# assert_xpath("//a[foo(., @href)]", @parser.parse('a:foo(@href)'))
-
# assert_xpath("//a[foo(., @a, b)]", @parser.parse('a:foo(@a, b)'))
-
# assert_xpath("//a[foo(., a, 10)]", @parser.parse('a:foo(a, 10)'))
-
result = val
-
end
-
-
result
-
end
-
-
1
def _reduce_44(val, _values, result)
-
if val[1] == 'n'
-
result = Node.new(:AN_PLUS_B, val)
-
else
-
raise Racc::ParseError, "parse error on IDENT '#{val[1]}'"
-
end
-
-
result
-
end
-
-
1
def _reduce_45(val, _values, result)
-
# n+3, -n+3
-
if val[0] == 'n'
-
val.unshift("1")
-
result = Node.new(:AN_PLUS_B, val)
-
elsif val[0] == '-n'
-
val[0] = 'n'
-
val.unshift("-1")
-
result = Node.new(:AN_PLUS_B, val)
-
else
-
raise Racc::ParseError, "parse error on IDENT '#{val[1]}'"
-
end
-
-
result
-
end
-
-
1
def _reduce_46(val, _values, result)
-
if val[1] == 'n'
-
val << "+"
-
val << "0"
-
result = Node.new(:AN_PLUS_B, val)
-
else
-
raise Racc::ParseError, "parse error on IDENT '#{val[1]}'"
-
end
-
-
result
-
end
-
-
1
def _reduce_47(val, _values, result)
-
result = Node.new(:PSEUDO_CLASS, [val[1]])
-
-
result
-
end
-
-
1
def _reduce_48(val, _values, result)
-
result = Node.new(:PSEUDO_CLASS, [val[1]])
-
result
-
end
-
-
# reduce 49 omitted
-
-
# reduce 50 omitted
-
-
1
def _reduce_51(val, _values, result)
-
result = Node.new(:COMBINATOR, val)
-
-
result
-
end
-
-
1
def _reduce_52(val, _values, result)
-
result = Node.new(:COMBINATOR, val)
-
-
result
-
end
-
-
1
def _reduce_53(val, _values, result)
-
result = Node.new(:COMBINATOR, val)
-
-
result
-
end
-
-
1
def _reduce_54(val, _values, result)
-
result = Node.new(:COMBINATOR, val)
-
-
result
-
end
-
-
# reduce 55 omitted
-
-
# reduce 56 omitted
-
-
# reduce 57 omitted
-
-
# reduce 58 omitted
-
-
1
def _reduce_59(val, _values, result)
-
result = Node.new(:ID, val)
-
result
-
end
-
-
1
def _reduce_60(val, _values, result)
-
result = [val.first, val[1]]
-
result
-
end
-
-
1
def _reduce_61(val, _values, result)
-
result = [val.first, val[1]]
-
result
-
end
-
-
# reduce 62 omitted
-
-
1
def _reduce_63(val, _values, result)
-
result = :equal
-
result
-
end
-
-
1
def _reduce_64(val, _values, result)
-
result = :prefix_match
-
result
-
end
-
-
1
def _reduce_65(val, _values, result)
-
result = :suffix_match
-
result
-
end
-
-
1
def _reduce_66(val, _values, result)
-
result = :substring_match
-
result
-
end
-
-
1
def _reduce_67(val, _values, result)
-
result = :not_equal
-
result
-
end
-
-
1
def _reduce_68(val, _values, result)
-
result = :includes
-
result
-
end
-
-
1
def _reduce_69(val, _values, result)
-
result = :dash_match
-
result
-
end
-
-
1
def _reduce_70(val, _values, result)
-
result = Node.new(:NOT, [val[1]])
-
-
result
-
end
-
-
# reduce 71 omitted
-
-
# reduce 72 omitted
-
-
# reduce 73 omitted
-
-
1
def _reduce_none(val, _values, result)
-
val[0]
-
end
-
-
end # class Parser
-
end # module CSS
-
end # module Nokogiri
-
1
require 'thread'
-
-
1
module Nokogiri
-
1
module CSS
-
1
class Parser < Racc::Parser
-
1
@cache_on = true
-
1
@cache = {}
-
1
@mutex = Mutex.new
-
-
1
class << self
-
# Turn on CSS parse caching
-
1
attr_accessor :cache_on
-
1
alias :cache_on? :cache_on
-
1
alias :set_cache :cache_on=
-
-
# Get the css selector in +string+ from the cache
-
1
def [] string
-
return unless @cache_on
-
@mutex.synchronize { @cache[string] }
-
end
-
-
# Set the css selector in +string+ in the cache to +value+
-
1
def []= string, value
-
return value unless @cache_on
-
@mutex.synchronize { @cache[string] = value }
-
end
-
-
# Clear the cache
-
1
def clear_cache
-
@mutex.synchronize { @cache = {} }
-
end
-
-
# Execute +block+ without cache
-
1
def without_cache &block
-
tmp = @cache_on
-
@cache_on = false
-
block.call
-
@cache_on = tmp
-
end
-
-
###
-
# Parse this CSS selector in +selector+. Returns an AST.
-
1
def parse selector
-
@warned ||= false
-
unless @warned
-
$stderr.puts('Nokogiri::CSS::Parser.parse is deprecated, call Nokogiri::CSS.parse(), this will be removed August 1st or version 1.4.0 (whichever is first)')
-
@warned = true
-
end
-
new.parse selector
-
end
-
end
-
-
# Create a new CSS parser with respect to +namespaces+
-
1
def initialize namespaces = {}
-
@tokenizer = Tokenizer.new
-
@namespaces = namespaces
-
super()
-
end
-
-
1
def parse string
-
@tokenizer.scan_setup string
-
do_parse
-
end
-
-
1
def next_token
-
@tokenizer.next_token
-
end
-
-
# Get the xpath for +string+ using +options+
-
1
def xpath_for string, options={}
-
key = "#{string}#{options[:ns]}#{options[:prefix]}"
-
v = self.class[key]
-
return v if v
-
-
args = [
-
options[:prefix] || '//',
-
options[:visitor] || XPathVisitor.new
-
]
-
self.class[key] = parse(string).map { |ast|
-
ast.to_xpath(*args)
-
}
-
end
-
-
# On CSS parser error, raise an exception
-
1
def on_error error_token_id, error_value, value_stack
-
after = value_stack.compact.last
-
raise SyntaxError.new("unexpected '#{error_value}' after '#{after}'")
-
end
-
end
-
end
-
end
-
1
require 'nokogiri/syntax_error'
-
1
module Nokogiri
-
1
module CSS
-
1
class SyntaxError < ::Nokogiri::SyntaxError
-
end
-
end
-
end
-
#--
-
# DO NOT MODIFY!!!!
-
# This file is automatically generated by rex 1.0.5
-
# from lexical definition file "lib/nokogiri/css/tokenizer.rex".
-
#++
-
-
1
module Nokogiri
-
1
module CSS
-
1
class Tokenizer # :nodoc:
-
1
require 'strscan'
-
-
1
class ScanError < StandardError ; end
-
-
1
attr_reader :lineno
-
1
attr_reader :filename
-
1
attr_accessor :state
-
-
1
def scan_setup(str)
-
@ss = StringScanner.new(str)
-
@lineno = 1
-
@state = nil
-
end
-
-
1
def action
-
yield
-
end
-
-
1
def scan_str(str)
-
scan_setup(str)
-
do_parse
-
end
-
1
alias :scan :scan_str
-
-
1
def load_file( filename )
-
@filename = filename
-
open(filename, "r") do |f|
-
scan_setup(f.read)
-
end
-
end
-
-
1
def scan_file( filename )
-
load_file(filename)
-
do_parse
-
end
-
-
-
1
def next_token
-
return if @ss.eos?
-
-
# skips empty actions
-
until token = _next_token or @ss.eos?; end
-
token
-
end
-
-
1
def _next_token
-
text = @ss.peek(1)
-
@lineno += 1 if text == "\n"
-
token = case @state
-
when nil
-
case
-
when (text = @ss.scan(/has\([\s]*/))
-
action { [:HAS, text] }
-
-
when (text = @ss.scan(/[-@]?([_A-Za-z]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])([_A-Za-z0-9-]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*\([\s]*/))
-
action { [:FUNCTION, text] }
-
-
when (text = @ss.scan(/[-@]?([_A-Za-z]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])([_A-Za-z0-9-]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*/))
-
action { [:IDENT, text] }
-
-
when (text = @ss.scan(/\#([_A-Za-z0-9-]|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])+/))
-
action { [:HASH, text] }
-
-
when (text = @ss.scan(/[\s]*~=[\s]*/))
-
action { [:INCLUDES, text] }
-
-
when (text = @ss.scan(/[\s]*\|=[\s]*/))
-
action { [:DASHMATCH, text] }
-
-
when (text = @ss.scan(/[\s]*\^=[\s]*/))
-
action { [:PREFIXMATCH, text] }
-
-
when (text = @ss.scan(/[\s]*\$=[\s]*/))
-
action { [:SUFFIXMATCH, text] }
-
-
when (text = @ss.scan(/[\s]*\*=[\s]*/))
-
action { [:SUBSTRINGMATCH, text] }
-
-
when (text = @ss.scan(/[\s]*!=[\s]*/))
-
action { [:NOT_EQUAL, text] }
-
-
when (text = @ss.scan(/[\s]*=[\s]*/))
-
action { [:EQUAL, text] }
-
-
when (text = @ss.scan(/[\s]*\)/))
-
action { [:RPAREN, text] }
-
-
when (text = @ss.scan(/[\s]*\[[\s]*/))
-
action { [:LSQUARE, text] }
-
-
when (text = @ss.scan(/[\s]*\]/))
-
action { [:RSQUARE, text] }
-
-
when (text = @ss.scan(/[\s]*\+[\s]*/))
-
action { [:PLUS, text] }
-
-
when (text = @ss.scan(/[\s]*>[\s]*/))
-
action { [:GREATER, text] }
-
-
when (text = @ss.scan(/[\s]*,[\s]*/))
-
action { [:COMMA, text] }
-
-
when (text = @ss.scan(/[\s]*~[\s]*/))
-
action { [:TILDE, text] }
-
-
when (text = @ss.scan(/\:not\([\s]*/))
-
action { [:NOT, text] }
-
-
when (text = @ss.scan(/-?([0-9]+|[0-9]*\.[0-9]+)/))
-
action { [:NUMBER, text] }
-
-
when (text = @ss.scan(/[\s]*\/\/[\s]*/))
-
action { [:DOUBLESLASH, text] }
-
-
when (text = @ss.scan(/[\s]*\/[\s]*/))
-
action { [:SLASH, text] }
-
-
when (text = @ss.scan(/U\+[0-9a-f?]{1,6}(-[0-9a-f]{1,6})?/))
-
action {[:UNICODE_RANGE, text] }
-
-
when (text = @ss.scan(/[\s]+/))
-
action { [:S, text] }
-
-
when (text = @ss.scan(/"([^\n\r\f"]|\n|\r\n|\r|\f|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*"|'([^\n\r\f']|\n|\r\n|\r|\f|[^\0-\177]|\\[0-9A-Fa-f]{1,6}(\r\n|[\s])?|\\[^\n\r\f0-9A-Fa-f])*'/))
-
action { [:STRING, text] }
-
-
when (text = @ss.scan(/./))
-
action { [text, text] }
-
-
else
-
text = @ss.string[@ss.pos .. -1]
-
raise ScanError, "can not match: '" + text + "'"
-
end # if
-
-
else
-
raise ScanError, "undefined state: '" + state.to_s + "'"
-
end # case state
-
token
-
end # def _next_token
-
-
end # class
-
end
-
end
-
1
module Nokogiri
-
1
module CSS
-
1
class XPathVisitor # :nodoc:
-
1
def visit_function node
-
# note that nth-child and nth-last-child are preprocessed in css/node.rb.
-
msg = :"visit_function_#{node.value.first.gsub(/[(]/, '')}"
-
return self.send(msg, node) if self.respond_to?(msg)
-
-
case node.value.first
-
when /^text\(/
-
'child::text()'
-
when /^self\(/
-
"self::#{node.value[1]}"
-
when /^eq\(/
-
"position() = #{node.value[1]}"
-
when /^(nth|nth-of-type|nth-child)\(/
-
if node.value[1].is_a?(Nokogiri::CSS::Node) and node.value[1].type == :AN_PLUS_B
-
an_plus_b(node.value[1])
-
else
-
"position() = #{node.value[1]}"
-
end
-
when /^(nth-last-child|nth-last-of-type)\(/
-
if node.value[1].is_a?(Nokogiri::CSS::Node) and node.value[1].type == :AN_PLUS_B
-
an_plus_b(node.value[1], :last => true)
-
else
-
index = node.value[1].to_i - 1
-
index == 0 ? "position() = last()" : "position() = last() - #{index}"
-
end
-
when /^(first|first-of-type)\(/
-
"position() = 1"
-
when /^(last|last-of-type)\(/
-
"position() = last()"
-
when /^contains\(/
-
"contains(., #{node.value[1]})"
-
when /^gt\(/
-
"position() > #{node.value[1]}"
-
when /^only-child\(/
-
"last() = 1"
-
when /^comment\(/
-
"comment()"
-
when /^has\(/
-
node.value[1].accept(self)
-
else
-
args = ['.'] + node.value[1..-1]
-
"#{node.value.first}#{args.join(', ')})"
-
end
-
end
-
-
1
def visit_not node
-
child = node.value.first
-
if :ELEMENT_NAME == child.type
-
"not(self::#{child.accept(self)})"
-
else
-
"not(#{child.accept(self)})"
-
end
-
end
-
-
1
def visit_id node
-
node.value.first =~ /^#(.*)$/
-
"@id = '#{$1}'"
-
end
-
-
1
def visit_attribute_condition node
-
attribute = if (node.value.first.type == :FUNCTION) or (node.value.first.value.first =~ /::/)
-
''
-
else
-
'@'
-
end
-
attribute += node.value.first.accept(self)
-
-
# Support non-standard css
-
attribute.gsub!(/^@@/, '@')
-
-
return attribute unless node.value.length == 3
-
-
value = node.value.last
-
value = "'#{value}'" if value !~ /^['"]/
-
-
case node.value[1]
-
when :equal
-
attribute + " = " + "#{value}"
-
when :not_equal
-
attribute + " != " + "#{value}"
-
when :substring_match
-
"contains(#{attribute}, #{value})"
-
when :prefix_match
-
"starts-with(#{attribute}, #{value})"
-
when :dash_match
-
"#{attribute} = #{value} or starts-with(#{attribute}, concat(#{value}, '-'))"
-
when :includes
-
"contains(concat(\" \", #{attribute}, \" \"),concat(\" \", #{value}, \" \"))"
-
when :suffix_match
-
"substring(#{attribute}, string-length(#{attribute}) - " +
-
"string-length(#{value}) + 1, string-length(#{value})) = #{value}"
-
else
-
attribute + " #{node.value[1]} " + "#{value}"
-
end
-
end
-
-
1
def visit_pseudo_class node
-
if node.value.first.is_a?(Nokogiri::CSS::Node) and node.value.first.type == :FUNCTION
-
node.value.first.accept(self)
-
else
-
msg = :"visit_pseudo_class_#{node.value.first.gsub(/[(]/, '')}"
-
return self.send(msg, node) if self.respond_to?(msg)
-
-
case node.value.first
-
when "first", "first-child" then "position() = 1"
-
when "last", "last-child" then "position() = last()"
-
when "first-of-type" then "position() = 1"
-
when "last-of-type" then "position() = last()"
-
when "only-of-type" then "last() = 1"
-
when "empty" then "not(node())"
-
when "parent" then "node()"
-
when "root" then "not(parent::*)"
-
else
-
node.value.first + "(.)"
-
end
-
end
-
end
-
-
1
def visit_class_condition node
-
"contains(concat(' ', @class, ' '), ' #{node.value.first} ')"
-
end
-
-
{
-
'combinator' => ' and ',
-
'direct_adjacent_selector' => "/following-sibling::*[1]/self::",
-
'following_selector' => "/following-sibling::",
-
'descendant_selector' => '//',
-
'child_selector' => '/',
-
1
}.each do |k,v|
-
class_eval %{
-
def visit_#{k} node
-
"\#{node.value.first.accept(self) if node.value.first}#{v}\#{node.value.last.accept(self)}"
-
end
-
5
}
-
end
-
-
1
def visit_conditional_selector node
-
node.value.first.accept(self) + '[' +
-
node.value.last.accept(self) + ']'
-
end
-
-
1
def visit_element_name node
-
node.value.first
-
end
-
-
1
def accept node
-
node.accept(self)
-
end
-
-
1
private
-
1
def an_plus_b node, options={}
-
raise ArgumentError, "expected an+b node to contain 4 tokens, but is #{node.value.inspect}" unless node.value.size == 4
-
-
a = node.value[0].to_i
-
b = node.value[3].to_i
-
position = options[:last] ? "(last()-position()+1)" : "position()"
-
-
if (b == 0)
-
return "(#{position} mod #{a}) = 0"
-
else
-
compare = (a < 0) ? "<=" : ">="
-
return "(#{position} #{compare} #{b}) and (((#{position}-#{b}) mod #{a.abs}) = 0)"
-
end
-
end
-
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module Decorators
-
###
-
# The Slop decorator implements method missing such that a methods may be
-
# used instead of XPath or CSS. See Nokogiri.Slop
-
1
module Slop
-
###
-
# look for node with +name+. See Nokogiri.Slop
-
1
def method_missing name, *args, &block
-
prefix = implied_xpath_context
-
-
if args.empty?
-
list = xpath("#{prefix}#{name.to_s.sub(/^_/, '')}")
-
elsif args.first.is_a? Hash
-
hash = args.first
-
if hash[:css]
-
list = css("#{name}#{hash[:css]}")
-
elsif hash[:xpath]
-
conds = Array(hash[:xpath]).join(' and ')
-
list = xpath("#{prefix}#{name}[#{conds}]")
-
end
-
else
-
CSS::Parser.without_cache do
-
list = xpath(
-
*CSS.xpath_for("#{name}#{args.first}", :prefix => prefix)
-
)
-
end
-
end
-
-
super if list.empty?
-
list.length == 1 ? list.first : list
-
end
-
end
-
end
-
end
-
1
require 'nokogiri/html/entity_lookup'
-
1
require 'nokogiri/html/document'
-
1
require 'nokogiri/html/document_fragment'
-
1
require 'nokogiri/html/sax/parser_context'
-
1
require 'nokogiri/html/sax/parser'
-
1
require 'nokogiri/html/sax/push_parser'
-
1
require 'nokogiri/html/element_description'
-
1
require 'nokogiri/html/element_description_defaults'
-
-
1
module Nokogiri
-
1
class << self
-
###
-
# Parse HTML. Convenience method for Nokogiri::HTML::Document.parse
-
1
def HTML thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML, &block
-
Nokogiri::HTML::Document.parse(thing, url, encoding, options, &block)
-
end
-
end
-
-
1
module HTML
-
1
class << self
-
###
-
# Parse HTML. Convenience method for Nokogiri::HTML::Document.parse
-
1
def parse thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML, &block
-
Document.parse(thing, url, encoding, options, &block)
-
end
-
-
####
-
# Parse a fragment from +string+ in to a NodeSet.
-
1
def fragment string, encoding = nil
-
HTML::DocumentFragment.parse string, encoding
-
end
-
end
-
-
# Instance of Nokogiri::HTML::EntityLookup
-
1
NamedCharacters = EntityLookup.new
-
end
-
end
-
1
module Nokogiri
-
1
module HTML
-
###
-
# Nokogiri HTML builder is used for building HTML documents. It is very
-
# similar to the Nokogiri::XML::Builder. In fact, you should go read the
-
# documentation for Nokogiri::XML::Builder before reading this
-
# documentation.
-
#
-
# == Synopsis:
-
#
-
# Create an HTML document with a body that has an onload attribute, and a
-
# span tag with a class of "bold" that has content of "Hello world".
-
#
-
# builder = Nokogiri::HTML::Builder.new do |doc|
-
# doc.html {
-
# doc.body(:onload => 'some_func();') {
-
# doc.span.bold {
-
# doc.text "Hello world"
-
# }
-
# }
-
# }
-
# end
-
# puts builder.to_html
-
#
-
# The HTML builder inherits from the XML builder, so make sure to read the
-
# Nokogiri::XML::Builder documentation.
-
1
class Builder < Nokogiri::XML::Builder
-
###
-
# Convert the builder to HTML
-
1
def to_html
-
@doc.to_html
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module HTML
-
1
class Document < Nokogiri::XML::Document
-
###
-
# Get the meta tag encoding for this document. If there is no meta tag,
-
# then nil is returned.
-
1
def meta_encoding
-
meta = meta_content_type and
-
match = /charset\s*=\s*([\w-]+)/i.match(meta['content']) and
-
match[1]
-
end
-
-
###
-
# Set the meta tag encoding for this document. If there is no meta
-
# content tag, the encoding is not set.
-
1
def meta_encoding= encoding
-
meta = meta_content_type and
-
meta['content'] = "text/html; charset=%s" % encoding
-
end
-
-
1
def meta_content_type
-
css('meta[@http-equiv]').find { |node|
-
node['http-equiv'] =~ /\AContent-Type\z/i and
-
!node['content'].nil? and
-
!node['content'].empty?
-
}
-
end
-
1
private :meta_content_type
-
-
###
-
# Get the title string of this document. Return nil if there is
-
# no title tag.
-
1
def title
-
title = at('title') and title.inner_text
-
end
-
-
###
-
# Set the title string of this document. If there is no head
-
# element, the title is not set.
-
1
def title=(text)
-
unless title = at('title')
-
head = at('head') or return nil
-
title = Nokogiri::XML::Node.new('title', self)
-
head << title
-
end
-
title.children = XML::Text.new(text, self)
-
end
-
-
####
-
# Serialize Node using +options+. Save options can also be set using a
-
# block. See SaveOptions.
-
#
-
# These two statements are equivalent:
-
#
-
# node.serialize(:encoding => 'UTF-8', :save_with => FORMAT | AS_XML)
-
#
-
# or
-
#
-
# node.serialize(:encoding => 'UTF-8') do |config|
-
# config.format.as_xml
-
# end
-
#
-
1
def serialize options = {}
-
options[:save_with] ||= XML::Node::SaveOptions::DEFAULT_HTML
-
super
-
end
-
-
####
-
# Create a Nokogiri::XML::DocumentFragment from +tags+
-
1
def fragment tags = nil
-
DocumentFragment.new(self, tags, self.root)
-
end
-
-
1
class << self
-
###
-
# Parse HTML. +string_or_io+ may be a String, or any object that
-
# responds to _read_ and _close_ such as an IO, or StringIO.
-
# +url+ is resource where this document is located. +encoding+ is the
-
# encoding that should be used when processing the document. +options+
-
# is a number that sets options in the parser, such as
-
# Nokogiri::XML::ParseOptions::RECOVER. See the constants in
-
# Nokogiri::XML::ParseOptions.
-
1
def parse string_or_io, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML
-
-
options = Nokogiri::XML::ParseOptions.new(options) if Fixnum === options
-
# Give the options to the user
-
yield options if block_given?
-
-
if string_or_io.respond_to?(:encoding)
-
unless string_or_io.encoding.name == "ASCII-8BIT"
-
encoding ||= string_or_io.encoding.name
-
end
-
end
-
-
if string_or_io.respond_to?(:read)
-
url ||= string_or_io.respond_to?(:path) ? string_or_io.path : nil
-
if !encoding
-
# Libxml2's parser has poor support for encoding
-
# detection. First, it does not recognize the HTML5
-
# style meta charset declaration. Secondly, even if it
-
# successfully detects an encoding hint, it does not
-
# re-decode or re-parse the preceding part which may be
-
# garbled.
-
#
-
# EncodingReader aims to perform advanced encoding
-
# detection beyond what Libxml2 does, and to emulate
-
# rewinding of a stream and make Libxml2 redo parsing
-
# from the start when an encoding hint is found.
-
string_or_io = EncodingReader.new(string_or_io)
-
begin
-
return read_io(string_or_io, url, encoding, options.to_i)
-
rescue EncodingFound => e
-
encoding = e.found_encoding
-
end
-
end
-
return read_io(string_or_io, url, encoding, options.to_i)
-
end
-
-
# read_memory pukes on empty docs
-
return new if string_or_io.nil? or string_or_io.empty?
-
-
encoding ||= EncodingReader.detect_encoding(string_or_io)
-
-
read_memory(string_or_io, url, encoding, options.to_i)
-
end
-
end
-
-
1
class EncodingFound < StandardError # :nodoc:
-
1
attr_reader :found_encoding
-
-
1
def initialize(encoding)
-
@found_encoding = encoding
-
super("encoding found: %s" % encoding)
-
end
-
end
-
-
1
class EncodingReader # :nodoc:
-
1
class SAXHandler < Nokogiri::XML::SAX::Document # :nodoc:
-
1
attr_reader :encoding
-
-
1
def initialize
-
@encoding = nil
-
super()
-
end
-
-
1
def start_element(name, attrs = [])
-
return unless name == 'meta'
-
attr = Hash[attrs]
-
charset = attr['charset'] and
-
@encoding = charset
-
http_equiv = attr['http-equiv'] and
-
http_equiv.match(/\AContent-Type\z/i) and
-
content = attr['content'] and
-
m = content.match(/;\s*charset\s*=\s*([\w-]+)/) and
-
@encoding = m[1]
-
end
-
end
-
-
1
class JumpSAXHandler < SAXHandler
-
1
def initialize(jumptag)
-
@jumptag = jumptag
-
super()
-
end
-
-
1
def start_element(name, attrs = [])
-
super
-
throw @jumptag, @encoding if @encoding
-
throw @jumptag, nil if name =~ /\A(?:div|h1|img|p|br)\z/
-
end
-
end
-
-
1
def self.detect_encoding(chunk)
-
if Nokogiri.jruby? && EncodingReader.is_jruby_without_fix?
-
return EncodingReader.detect_encoding_for_jruby_without_fix(chunk)
-
end
-
m = chunk.match(/\A(<\?xml[ \t\r\n]+[^>]*>)/) and
-
return Nokogiri.XML(m[1]).encoding
-
-
if Nokogiri.jruby?
-
m = chunk.match(/(<meta\s)(.*)(charset\s*=\s*([\w-]+))(.*)/i) and
-
return m[4]
-
catch(:encoding_found) {
-
Nokogiri::HTML::SAX::Parser.new(JumpSAXHandler.new(:encoding_found)).parse(chunk)
-
nil
-
}
-
else
-
handler = SAXHandler.new
-
parser = Nokogiri::HTML::SAX::PushParser.new(handler)
-
parser << chunk rescue Nokogiri::SyntaxError
-
handler.encoding
-
end
-
end
-
-
1
def self.is_jruby_without_fix?
-
JRUBY_VERSION.split('.').join.to_i < 165
-
end
-
-
1
def self.detect_encoding_for_jruby_without_fix(chunk)
-
m = chunk.match(/\A(<\?xml[ \t\r\n]+[^>]*>)/) and
-
return Nokogiri.XML(m[1]).encoding
-
-
m = chunk.match(/(<meta\s)(.*)(charset\s*=\s*([\w-]+))(.*)/i) and
-
return m[4]
-
-
catch(:encoding_found) {
-
Nokogiri::HTML::SAX::Parser.new(JumpSAXHandler.new(:encoding_found.to_s)).parse(chunk)
-
nil
-
}
-
rescue Nokogiri::SyntaxError, RuntimeError
-
# Ignore parser errors that nokogiri may raise
-
nil
-
end
-
-
1
def initialize(io)
-
@io = io
-
@firstchunk = nil
-
@encoding_found = nil
-
end
-
-
# This method is used by the C extension so that
-
# Nokogiri::HTML::Document#read_io() does not leak memory when
-
# EncodingFound is raised.
-
1
attr_reader :encoding_found
-
-
1
def read(len)
-
# no support for a call without len
-
-
if !@firstchunk
-
@firstchunk = @io.read(len) or return nil
-
-
# This implementation expects that the first call from
-
# htmlReadIO() is made with a length long enough (~1KB) to
-
# achieve advanced encoding detection.
-
if encoding = EncodingReader.detect_encoding(@firstchunk)
-
# The first chunk is stored for the next read in retry.
-
raise @encoding_found = EncodingFound.new(encoding)
-
end
-
end
-
@encoding_found = nil
-
-
ret = @firstchunk.slice!(0, len)
-
if (len -= ret.length) > 0
-
rest = @io.read(len) and ret << rest
-
end
-
if ret.empty?
-
nil
-
else
-
ret
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module HTML
-
1
class DocumentFragment < Nokogiri::XML::DocumentFragment
-
1
attr_accessor :errors
-
-
####
-
# Create a Nokogiri::XML::DocumentFragment from +tags+, using +encoding+
-
1
def self.parse tags, encoding = nil
-
doc = HTML::Document.new
-
-
encoding ||= tags.respond_to?(:encoding) ? tags.encoding.name : 'UTF-8'
-
doc.encoding = encoding
-
-
new(doc, tags)
-
end
-
-
1
def initialize document, tags = nil, ctx = nil
-
return self unless tags
-
-
if ctx
-
preexisting_errors = document.errors.dup
-
node_set = ctx.parse("<div>#{tags}</div>")
-
node_set.first.children.each { |child| child.parent = self } unless node_set.empty?
-
self.errors = document.errors - preexisting_errors
-
else
-
# This is a horrible hack, but I don't care
-
if tags.strip =~ /^<body/i
-
path = "/html/body"
-
else
-
path = "/html/body/node()"
-
end
-
-
temp_doc = HTML::Document.parse "<html><body>#{tags}", nil, document.encoding
-
temp_doc.xpath(path).each { |child| child.parent = self }
-
self.errors = temp_doc.errors
-
end
-
children
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module HTML
-
1
class ElementDescription
-
###
-
# Is this element a block element?
-
1
def block?
-
!inline?
-
end
-
-
###
-
# Convert this description to a string
-
1
def to_s
-
"#{name}: #{description}"
-
end
-
-
###
-
# Inspection information
-
1
def inspect
-
"#<#{self.class.name}: #{name} #{description}>"
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module HTML
-
1
class ElementDescription
-
-
# Methods are defined protected by method_defined? because at
-
# this point the C-library or Java library is already loaded,
-
# and we don't want to clobber any methods that have been
-
# defined there.
-
-
1
Desc = Struct.new("HTMLElementDescription", :name,
-
:startTag, :endTag, :saveEndTag,
-
:empty, :depr, :dtd, :isinline,
-
:desc,
-
:subelts, :defaultsubelt,
-
:attrs_opt, :attrs_depr, :attrs_req)
-
-
# This is filled in down below.
-
1
DefaultDescriptions = Hash.new()
-
-
1
def default_desc
-
DefaultDescriptions[name.downcase]
-
end
-
1
private :default_desc
-
-
1
unless method_defined? :implied_start_tag?
-
def implied_start_tag?
-
d = default_desc
-
d ? d.startTag : nil
-
end
-
end
-
-
1
unless method_defined? :implied_end_tag?
-
def implied_end_tag?
-
d = default_desc
-
d ? d.endTag : nil
-
end
-
end
-
-
1
unless method_defined? :save_end_tag?
-
def save_end_tag?
-
d = default_desc
-
d ? d.saveEndTag : nil
-
end
-
end
-
-
1
unless method_defined? :deprecated?
-
def deprecated?
-
d = default_desc
-
d ? d.depr : nil
-
end
-
end
-
-
1
unless method_defined? :description
-
def description
-
d = default_desc
-
d ? d.desc : nil
-
end
-
end
-
-
1
unless method_defined? :default_sub_element
-
def default_sub_element
-
d = default_desc
-
d ? d.defaultsubelt : nil
-
end
-
end
-
-
1
unless method_defined? :optional_attributes
-
def optional_attributes
-
d = default_desc
-
d ? d.attrs_opt : []
-
end
-
end
-
-
1
unless method_defined? :deprecated_attributes
-
def deprecated_attributes
-
d = default_desc
-
d ? d.attrs_depr : []
-
end
-
end
-
-
1
unless method_defined? :required_attributes
-
def required_attributes
-
d = default_desc
-
d ? d.attrs_req : []
-
end
-
end
-
-
###
-
# Default Element Descriptions (HTML 4.0) copied from
-
# libxml2/HTMLparser.c and libxml2/include/libxml/HTMLparser.h
-
#
-
# The copyright notice for those files and the following list of
-
# element and attribute descriptions is reproduced here:
-
#
-
# Except where otherwise noted in the source code (e.g. the
-
# files hash.c, list.c and the trio files, which are covered by
-
# a similar licence but with different Copyright notices) all
-
# the files are:
-
#
-
# Copyright (C) 1998-2003 Daniel Veillard. All Rights Reserved.
-
#
-
# Permission is hereby granted, free of charge, to any person
-
# obtaining a copy of this software and associated documentation
-
# files (the "Software"), to deal in the Software without
-
# restriction, including without limitation the rights to use,
-
# copy, modify, merge, publish, distribute, sublicense, and/or
-
# sell copies of the Software, and to permit persons to whom the
-
# Software is fur- nished to do so, subject to the following
-
# conditions:
-
-
# The above copyright notice and this permission notice shall be
-
# included in all copies or substantial portions of the
-
# Software.
-
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
-
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
-
# WARRANTIES OF MERCHANTABILITY, FIT- NESS FOR A PARTICULAR
-
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE DANIEL
-
# VEILLARD BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-
# FROM, OUT OF OR IN CON- NECTION WITH THE SOFTWARE OR THE USE
-
# OR OTHER DEALINGS IN THE SOFTWARE.
-
-
# Except as contained in this notice, the name of Daniel
-
# Veillard shall not be used in advertising or otherwise to
-
# promote the sale, use or other deal- ings in this Software
-
# without prior written authorization from him.
-
-
# Attributes defined and categorized
-
1
FONTSTYLE = ["tt", "i", "b", "u", "s", "strike", "big", "small"]
-
1
PHRASE = ['em', 'strong', 'dfn', 'code', 'samp',
-
'kbd', 'var', 'cite', 'abbr', 'acronym']
-
1
SPECIAL = ['a', 'img', 'applet', 'embed', 'object', 'font','basefont',
-
'br', 'script', 'map', 'q', 'sub', 'sup', 'span', 'bdo',
-
'iframe']
-
1
PCDATA = []
-
1
HEADING = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']
-
1
LIST = ['ul', 'ol', 'dir', 'menu']
-
1
FORMCTRL = ['input', 'select', 'textarea', 'label', 'button']
-
1
BLOCK = [HEADING, LIST, 'pre', 'p', 'dl', 'div', 'center', 'noscript',
-
'noframes', 'blockquote', 'form', 'isindex', 'hr', 'table',
-
'fieldset', 'address']
-
1
INLINE = [PCDATA, FONTSTYLE, PHRASE, SPECIAL, FORMCTRL]
-
1
FLOW = [BLOCK, INLINE]
-
1
MODIFIER = []
-
1
EMPTY = []
-
-
1
HTML_FLOW = FLOW
-
1
HTML_INLINE = INLINE
-
1
HTML_PCDATA = PCDATA
-
1
HTML_CDATA = HTML_PCDATA
-
-
1
COREATTRS = ['id', 'class', 'style', 'title']
-
1
I18N = ['lang', 'dir']
-
1
EVENTS = ['onclick', 'ondblclick', 'onmousedown', 'onmouseup',
-
'onmouseover', 'onmouseout', 'onkeypress', 'onkeydown',
-
'onkeyup']
-
1
ATTRS = [COREATTRS, I18N,EVENTS]
-
1
CELLHALIGN = ['align', 'char', 'charoff']
-
1
CELLVALIGN = ['valign']
-
-
1
HTML_ATTRS = ATTRS
-
1
CORE_I18N_ATTRS = [COREATTRS, I18N]
-
1
CORE_ATTRS = COREATTRS
-
1
I18N_ATTRS = I18N
-
-
-
1
A_ATTRS = [ATTRS, 'charset', 'type', 'name',
-
'href', 'hreflang', 'rel', 'rev', 'accesskey', 'shape',
-
'coords', 'tabindex', 'onfocus', 'onblur']
-
1
TARGET_ATTR = ['target']
-
1
ROWS_COLS_ATTR = ['rows', 'cols']
-
1
ALT_ATTR = ['alt']
-
1
SRC_ALT_ATTRS = ['src', 'alt']
-
1
HREF_ATTRS = ['href']
-
1
CLEAR_ATTRS = ['clear']
-
1
INLINE_P = [INLINE, 'p']
-
-
1
FLOW_PARAM = [FLOW, 'param']
-
1
APPLET_ATTRS = [COREATTRS , 'codebase',
-
'archive', 'alt', 'name', 'height', 'width', 'align',
-
'hspace', 'vspace']
-
1
AREA_ATTRS = ['shape', 'coords', 'href', 'nohref',
-
'tabindex', 'accesskey', 'onfocus', 'onblur']
-
1
BASEFONT_ATTRS = ['id', 'size', 'color', 'face']
-
1
QUOTE_ATTRS = [ATTRS, 'cite']
-
1
BODY_CONTENTS = [FLOW, 'ins', 'del']
-
1
BODY_ATTRS = [ATTRS, 'onload', 'onunload']
-
1
BODY_DEPR = ['background', 'bgcolor', 'text',
-
'link', 'vlink', 'alink']
-
1
BUTTON_ATTRS = [ATTRS, 'name', 'value', 'type',
-
'disabled', 'tabindex', 'accesskey', 'onfocus', 'onblur']
-
-
-
1
COL_ATTRS = [ATTRS, 'span', 'width', CELLHALIGN, CELLVALIGN]
-
1
COL_ELT = ['col']
-
1
EDIT_ATTRS = [ATTRS, 'datetime', 'cite']
-
1
COMPACT_ATTRS = [ATTRS, 'compact']
-
1
DL_CONTENTS = ['dt', 'dd']
-
1
COMPACT_ATTR = ['compact']
-
1
LABEL_ATTR = ['label']
-
1
FIELDSET_CONTENTS = [FLOW, 'legend' ]
-
1
FONT_ATTRS = [COREATTRS, I18N, 'size', 'color', 'face' ]
-
1
FORM_CONTENTS = [HEADING, LIST, INLINE, 'pre', 'p', 'div', 'center',
-
'noscript', 'noframes', 'blockquote', 'isindex', 'hr',
-
'table', 'fieldset', 'address']
-
1
FORM_ATTRS = [ATTRS, 'method', 'enctype', 'accept', 'name', 'onsubmit',
-
'onreset', 'accept-charset']
-
1
FRAME_ATTRS = [COREATTRS, 'longdesc', 'name', 'src', 'frameborder',
-
'marginwidth', 'marginheight', 'noresize', 'scrolling' ]
-
1
FRAMESET_ATTRS = [COREATTRS, 'rows', 'cols', 'onload', 'onunload']
-
1
FRAMESET_CONTENTS = ['frameset', 'frame', 'noframes']
-
1
HEAD_ATTRS = [I18N, 'profile']
-
1
HEAD_CONTENTS = ['title', 'isindex', 'base', 'script', 'style', 'meta',
-
'link', 'object']
-
1
HR_DEPR = ['align', 'noshade', 'size', 'width']
-
1
VERSION_ATTR = ['version']
-
1
HTML_CONTENT = ['head', 'body', 'frameset']
-
1
IFRAME_ATTRS = [COREATTRS, 'longdesc', 'name', 'src', 'frameborder',
-
'marginwidth', 'marginheight', 'scrolling', 'align',
-
'height', 'width']
-
1
IMG_ATTRS = [ATTRS, 'longdesc', 'name', 'height', 'width', 'usemap',
-
'ismap']
-
1
EMBED_ATTRS = [COREATTRS, 'align', 'alt', 'border', 'code', 'codebase',
-
'frameborder', 'height', 'hidden', 'hspace', 'name',
-
'palette', 'pluginspace', 'pluginurl', 'src', 'type',
-
'units', 'vspace', 'width']
-
1
INPUT_ATTRS = [ATTRS, 'type', 'name', 'value', 'checked', 'disabled',
-
'readonly', 'size', 'maxlength', 'src', 'alt', 'usemap',
-
'ismap', 'tabindex', 'accesskey', 'onfocus', 'onblur',
-
'onselect', 'onchange', 'accept']
-
1
PROMPT_ATTRS = [COREATTRS, I18N, 'prompt']
-
1
LABEL_ATTRS = [ATTRS, 'for', 'accesskey', 'onfocus', 'onblur']
-
1
LEGEND_ATTRS = [ATTRS, 'accesskey']
-
1
ALIGN_ATTR = ['align']
-
1
LINK_ATTRS = [ATTRS, 'charset', 'href', 'hreflang', 'type', 'rel', 'rev',
-
'media']
-
1
MAP_CONTENTS = [BLOCK, 'area']
-
1
NAME_ATTR = ['name']
-
1
ACTION_ATTR = ['action']
-
1
BLOCKLI_ELT = [BLOCK, 'li']
-
1
META_ATTRS = [I18N, 'http-equiv', 'name', 'scheme']
-
1
CONTENT_ATTR = ['content']
-
1
TYPE_ATTR = ['type']
-
1
NOFRAMES_CONTENT = ['body', FLOW, MODIFIER]
-
1
OBJECT_CONTENTS = [FLOW, 'param']
-
1
OBJECT_ATTRS = [ATTRS, 'declare', 'classid', 'codebase', 'data', 'type',
-
'codetype', 'archive', 'standby', 'height', 'width',
-
'usemap', 'name', 'tabindex']
-
1
OBJECT_DEPR = ['align', 'border', 'hspace', 'vspace']
-
1
OL_ATTRS = ['type', 'compact', 'start']
-
1
OPTION_ELT = ['option']
-
1
OPTGROUP_ATTRS = [ATTRS, 'disabled']
-
1
OPTION_ATTRS = [ATTRS, 'disabled', 'label', 'selected', 'value']
-
1
PARAM_ATTRS = ['id', 'value', 'valuetype', 'type']
-
1
WIDTH_ATTR = ['width']
-
1
PRE_CONTENT = [PHRASE, 'tt', 'i', 'b', 'u', 's', 'strike', 'a', 'br',
-
'script', 'map', 'q', 'span', 'bdo', 'iframe']
-
1
SCRIPT_ATTRS = ['charset', 'src', 'defer', 'event', 'for']
-
1
LANGUAGE_ATTR = ['language']
-
1
SELECT_CONTENT = ['optgroup', 'option']
-
1
SELECT_ATTRS = [ATTRS, 'name', 'size', 'multiple', 'disabled', 'tabindex',
-
'onfocus', 'onblur', 'onchange']
-
1
STYLE_ATTRS = [I18N, 'media', 'title']
-
1
TABLE_ATTRS = [ATTRS, 'summary', 'width', 'border', 'frame', 'rules',
-
'cellspacing', 'cellpadding', 'datapagesize']
-
1
TABLE_DEPR = ['align', 'bgcolor']
-
1
TABLE_CONTENTS = ['caption', 'col', 'colgroup', 'thead', 'tfoot', 'tbody',
-
'tr']
-
1
TR_ELT = ['tr']
-
1
TALIGN_ATTRS = [ATTRS, CELLHALIGN, CELLVALIGN]
-
1
TH_TD_DEPR = ['nowrap', 'bgcolor', 'width', 'height']
-
1
TH_TD_ATTR = [ATTRS, 'abbr', 'axis', 'headers', 'scope', 'rowspan',
-
'colspan', CELLHALIGN, CELLVALIGN]
-
1
TEXTAREA_ATTRS = [ATTRS, 'name', 'disabled', 'readonly', 'tabindex',
-
'accesskey', 'onfocus', 'onblur', 'onselect',
-
'onchange']
-
1
TR_CONTENTS = ['th', 'td']
-
1
BGCOLOR_ATTR = ['bgcolor']
-
1
LI_ELT = ['li']
-
1
UL_DEPR = ['type', 'compact']
-
1
DIR_ATTR = ['dir']
-
-
[
-
['a', false, false, false, false, false, :any, true,
-
'anchor ',
-
HTML_INLINE, nil, A_ATTRS, TARGET_ATTR, []
-
1
],
-
['abbr', false, false, false, false, false, :any, true,
-
'abbreviated form',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['acronym', false, false, false, false, false, :any, true, '',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['address', false, false, false, false, false, :any, false,
-
'information on author',
-
INLINE_P , nil, HTML_ATTRS, [], []
-
],
-
['applet', false, false, false, false, true, :loose, true,
-
'java applet ',
-
FLOW_PARAM, nil, [], APPLET_ATTRS, []
-
],
-
['area', false, true, true, true, false, :any, false,
-
'client-side image map area ',
-
EMPTY, nil, AREA_ATTRS, TARGET_ATTR, ALT_ATTR
-
],
-
['b', false, true, false, false, false, :any, true,
-
'bold text style',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['base', false, true, true, true, false, :any, false,
-
'document base uri ',
-
EMPTY, nil, [], TARGET_ATTR, HREF_ATTRS
-
],
-
['basefont', false, true, true, true, true, :loose, true,
-
'base font size ',
-
EMPTY, nil, [], BASEFONT_ATTRS, []
-
],
-
['bdo', false, false, false, false, false, :any, true,
-
'i18n bidi over-ride ',
-
HTML_INLINE, nil, CORE_I18N_ATTRS, [], DIR_ATTR
-
],
-
['big', false, true, false, false, false, :any, true,
-
'large text style',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['blockquote', false, false, false, false, false, :any, false,
-
'long quotation ',
-
HTML_FLOW, nil, QUOTE_ATTRS, [], []
-
],
-
['body', true, true, false, false, false, :any, false,
-
'document body ',
-
BODY_CONTENTS, 'div', BODY_ATTRS, BODY_DEPR, []
-
],
-
['br', false, true, true, true, false, :any, true,
-
'forced line break ',
-
EMPTY, nil, CORE_ATTRS, CLEAR_ATTRS, []
-
],
-
['button', false, false, false, false, false, :any, true,
-
'push button ',
-
[HTML_FLOW, MODIFIER], nil, BUTTON_ATTRS, [], []
-
],
-
['caption', false, false, false, false, false, :any, false,
-
'table caption ',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['center', false, true, false, false, true, :loose, false,
-
'shorthand for div align=center ',
-
HTML_FLOW, nil, [], HTML_ATTRS, []
-
],
-
['cite', false, false, false, false, false, :any, true, 'citation',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['code', false, false, false, false, false, :any, true,
-
'computer code fragment',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['col', false, true, true, true, false, :any, false, 'table column ',
-
EMPTY, nil, COL_ATTRS, [], []
-
],
-
['colgroup', false, true, false, false, false, :any, false,
-
'table column group ',
-
COL_ELT, 'col', COL_ATTRS, [], []
-
],
-
['dd', false, true, false, false, false, :any, false,
-
'definition description ',
-
HTML_FLOW, nil, HTML_ATTRS, [], []
-
],
-
['del', false, false, false, false, false, :any, true,
-
'deleted text ',
-
HTML_FLOW, nil, EDIT_ATTRS, [], []
-
],
-
['dfn', false, false, false, false, false, :any, true,
-
'instance definition',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['dir', false, false, false, false, true, :loose, false,
-
'directory list',
-
BLOCKLI_ELT, 'li', [], COMPACT_ATTRS, []
-
],
-
['div', false, false, false, false, false, :any, false,
-
'generic language/style container',
-
HTML_FLOW, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['dl', false, false, false, false, false, :any, false,
-
'definition list ',
-
DL_CONTENTS, 'dd', HTML_ATTRS, COMPACT_ATTR, []
-
],
-
['dt', false, true, false, false, false, :any, false,
-
'definition term ',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['em', false, true, false, false, false, :any, true,
-
'emphasis',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['embed', false, true, false, false, true, :loose, true,
-
'generic embedded object ',
-
EMPTY, nil, EMBED_ATTRS, [], []
-
],
-
['fieldset', false, false, false, false, false, :any, false,
-
'form control group ',
-
FIELDSET_CONTENTS, nil, HTML_ATTRS, [], []
-
],
-
['font', false, true, false, false, true, :loose, true,
-
'local change to font ',
-
HTML_INLINE, nil, [], FONT_ATTRS, []
-
],
-
['form', false, false, false, false, false, :any, false,
-
'interactive form ',
-
FORM_CONTENTS, 'fieldset', FORM_ATTRS, TARGET_ATTR, ACTION_ATTR
-
],
-
['frame', false, true, true, true, false, :frameset, false,
-
'subwindow ',
-
EMPTY, nil, [], FRAME_ATTRS, []
-
],
-
['frameset', false, false, false, false, false, :frameset, false,
-
'window subdivision',
-
FRAMESET_CONTENTS, 'noframes', [], FRAMESET_ATTRS, []
-
],
-
['htrue', false, false, false, false, false, :any, false,
-
'heading ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['htrue', false, false, false, false, false, :any, false,
-
'heading ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['htrue', false, false, false, false, false, :any, false,
-
'heading ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['h4', false, false, false, false, false, :any, false,
-
'heading ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['h5', false, false, false, false, false, :any, false,
-
'heading ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['h6', false, false, false, false, false, :any, false,
-
'heading ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['head', true, true, false, false, false, :any, false,
-
'document head ',
-
HEAD_CONTENTS, nil, HEAD_ATTRS, [], []
-
],
-
['hr', false, true, true, true, false, :any, false,
-
'horizontal rule ',
-
EMPTY, nil, HTML_ATTRS, HR_DEPR, []
-
],
-
['html', true, true, false, false, false, :any, false,
-
'document root element ',
-
HTML_CONTENT, nil, I18N_ATTRS, VERSION_ATTR, []
-
],
-
['i', false, true, false, false, false, :any, true,
-
'italic text style',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['iframe', false, false, false, false, false, :any, true,
-
'inline subwindow ',
-
HTML_FLOW, nil, [], IFRAME_ATTRS, []
-
],
-
['img', false, true, true, true, false, :any, true,
-
'embedded image ',
-
EMPTY, nil, IMG_ATTRS, ALIGN_ATTR, SRC_ALT_ATTRS
-
],
-
['input', false, true, true, true, false, :any, true,
-
'form control ',
-
EMPTY, nil, INPUT_ATTRS, ALIGN_ATTR, []
-
],
-
['ins', false, false, false, false, false, :any, true,
-
'inserted text',
-
HTML_FLOW, nil, EDIT_ATTRS, [], []
-
],
-
['isindex', false, true, true, true, true, :loose, false,
-
'single line prompt ',
-
EMPTY, nil, [], PROMPT_ATTRS, []
-
],
-
['kbd', false, false, false, false, false, :any, true,
-
'text to be entered by the user',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['label', false, false, false, false, false, :any, true,
-
'form field label text ',
-
[HTML_INLINE, MODIFIER], nil, LABEL_ATTRS, [], []
-
],
-
['legend', false, false, false, false, false, :any, false,
-
'fieldset legend ',
-
HTML_INLINE, nil, LEGEND_ATTRS, ALIGN_ATTR, []
-
],
-
['li', false, true, true, false, false, :any, false,
-
'list item ',
-
HTML_FLOW, nil, HTML_ATTRS, [], []
-
],
-
['link', false, true, true, true, false, :any, false,
-
'a media-independent link ',
-
EMPTY, nil, LINK_ATTRS, TARGET_ATTR, []
-
],
-
['map', false, false, false, false, false, :any, true,
-
'client-side image map ',
-
MAP_CONTENTS, nil, HTML_ATTRS, [], NAME_ATTR
-
],
-
['menu', false, false, false, false, true, :loose, false,
-
'menu list ',
-
BLOCKLI_ELT, nil, [], COMPACT_ATTRS, []
-
],
-
['meta', false, true, true, true, false, :any, false,
-
'generic metainformation ',
-
EMPTY, nil, META_ATTRS, [], CONTENT_ATTR
-
],
-
['noframes', false, false, false, false, false, :frameset, false,
-
'alternate content container for non frame-based rendering ',
-
NOFRAMES_CONTENT, 'body', HTML_ATTRS, [], []
-
],
-
['noscript', false, false, false, false, false, :any, false,
-
'alternate content container for non script-based rendering ',
-
HTML_FLOW, 'div', HTML_ATTRS, [], []
-
],
-
['object', false, false, false, false, false, :any, true,
-
'generic embedded object ',
-
OBJECT_CONTENTS, 'div', OBJECT_ATTRS, OBJECT_DEPR, []
-
],
-
['ol', false, false, false, false, false, :any, false,
-
'ordered list ',
-
LI_ELT, 'li', HTML_ATTRS, OL_ATTRS, []
-
],
-
['optgroup', false, false, false, false, false, :any, false,
-
'option group ',
-
OPTION_ELT, 'option', OPTGROUP_ATTRS, [], LABEL_ATTR
-
],
-
['option', false, true, false, false, false, :any, false,
-
'selectable choice ',
-
HTML_PCDATA, nil, OPTION_ATTRS, [], []
-
],
-
['p', false, true, false, false, false, :any, false,
-
'paragraph ',
-
HTML_INLINE, nil, HTML_ATTRS, ALIGN_ATTR, []
-
],
-
['param', false, true, true, true, false, :any, false,
-
'named property value ',
-
EMPTY, nil, PARAM_ATTRS, [], NAME_ATTR
-
],
-
['pre', false, false, false, false, false, :any, false,
-
'preformatted text ',
-
PRE_CONTENT, nil, HTML_ATTRS, WIDTH_ATTR, []
-
],
-
['q', false, false, false, false, false, :any, true,
-
'short inline quotation ',
-
HTML_INLINE, nil, QUOTE_ATTRS, [], []
-
],
-
['s', false, true, false, false, true, :loose, true,
-
'strike-through text style',
-
HTML_INLINE, nil, [], HTML_ATTRS, []
-
],
-
['samp', false, false, false, false, false, :any, true,
-
'sample program output, scripts, etc.',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['script', false, false, false, false, false, :any, true,
-
'script statements ',
-
HTML_CDATA, nil, SCRIPT_ATTRS, LANGUAGE_ATTR, TYPE_ATTR
-
],
-
['select', false, false, false, false, false, :any, true,
-
'option selector ',
-
SELECT_CONTENT, nil, SELECT_ATTRS, [], []
-
],
-
['small', false, true, false, false, false, :any, true,
-
'small text style',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['span', false, false, false, false, false, :any, true,
-
'generic language/style container ',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['strike', false, true, false, false, true, :loose, true,
-
'strike-through text',
-
HTML_INLINE, nil, [], HTML_ATTRS, []
-
],
-
['strong', false, true, false, false, false, :any, true,
-
'strong emphasis',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['style', false, false, false, false, false, :any, false,
-
'style info ',
-
HTML_CDATA, nil, STYLE_ATTRS, [], TYPE_ATTR
-
],
-
['sub', false, true, false, false, false, :any, true,
-
'subscript',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['sup', false, true, false, false, false, :any, true,
-
'superscript ',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['table', false, false, false, false, false, :any, false,
-
'',
-
TABLE_CONTENTS, 'tr', TABLE_ATTRS, TABLE_DEPR, []
-
],
-
['tbody', true, false, false, false, false, :any, false,
-
'table body ',
-
TR_ELT, 'tr', TALIGN_ATTRS, [], []
-
],
-
['td', false, false, false, false, false, :any, false,
-
'table data cell',
-
HTML_FLOW, nil, TH_TD_ATTR, TH_TD_DEPR, []
-
],
-
['textarea', false, false, false, false, false, :any, true,
-
'multi-line text field ',
-
HTML_PCDATA, nil, TEXTAREA_ATTRS, [], ROWS_COLS_ATTR
-
],
-
['tfoot', false, true, false, false, false, :any, false,
-
'table footer ',
-
TR_ELT, 'tr', TALIGN_ATTRS, [], []
-
],
-
['th', false, true, false, false, false, :any, false,
-
'table header cell',
-
HTML_FLOW, nil, TH_TD_ATTR, TH_TD_DEPR, []
-
],
-
['thead', false, true, false, false, false, :any, false,
-
'table header ',
-
TR_ELT, 'tr', TALIGN_ATTRS, [], []
-
],
-
['title', false, false, false, false, false, :any, false,
-
'document title ',
-
HTML_PCDATA, nil, I18N_ATTRS, [], []
-
],
-
['tr', false, false, false, false, false, :any, false,
-
'table row ',
-
TR_CONTENTS, 'td', TALIGN_ATTRS, BGCOLOR_ATTR, []
-
],
-
['tt', false, true, false, false, false, :any, true,
-
'teletype or monospaced text style',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
],
-
['u', false, true, false, false, true, :loose, true,
-
'underlined text style',
-
HTML_INLINE, nil, [], HTML_ATTRS, []
-
],
-
['ul', false, false, false, false, false, :any, false,
-
'unordered list ',
-
LI_ELT, 'li', HTML_ATTRS, UL_DEPR, []
-
],
-
['var', false, false, false, false, false, :any, true,
-
'instance of a variable or program argument',
-
HTML_INLINE, nil, HTML_ATTRS, [], []
-
]
-
].each do |descriptor|
-
92
name = descriptor[0]
-
-
92
begin
-
92
d = Desc.new(*descriptor)
-
-
# flatten all the attribute lists (Ruby1.9, *[a,b,c] can be
-
# used to flatten a literal list, but not in Ruby1.8).
-
92
d[:subelts] = d[:subelts].flatten
-
92
d[:attrs_opt] = d[:attrs_opt].flatten
-
92
d[:attrs_depr] = d[:attrs_depr].flatten
-
92
d[:attrs_req] = d[:attrs_req].flatten
-
rescue => e
-
p name
-
raise e
-
end
-
-
92
DefaultDescriptions[name] = d
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module HTML
-
1
class EntityDescription < Struct.new(:value, :name, :description); end
-
-
1
class EntityLookup
-
###
-
# Look up entity with +name+
-
1
def [] name
-
(val = get(name)) && val.value
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module HTML
-
###
-
# Nokogiri lets you write a SAX parser to process HTML but get HTML
-
# correction features.
-
#
-
# See Nokogiri::HTML::SAX::Parser for a basic example of using a
-
# SAX parser with HTML.
-
#
-
# For more information on SAX parsers, see Nokogiri::XML::SAX
-
1
module SAX
-
###
-
# This class lets you perform SAX style parsing on HTML with HTML
-
# error correction.
-
#
-
# Here is a basic usage example:
-
#
-
# class MyDoc < Nokogiri::XML::SAX::Document
-
# def start_element name, attributes = []
-
# puts "found a #{name}"
-
# end
-
# end
-
#
-
# parser = Nokogiri::HTML::SAX::Parser.new(MyDoc.new)
-
# parser.parse(File.read(ARGV[0], 'rb'))
-
#
-
# For more information on SAX parsers, see Nokogiri::XML::SAX
-
1
class Parser < Nokogiri::XML::SAX::Parser
-
###
-
# Parse html stored in +data+ using +encoding+
-
1
def parse_memory data, encoding = 'UTF-8'
-
raise ArgumentError unless data
-
return unless data.length > 0
-
ctx = ParserContext.memory(data, encoding)
-
yield ctx if block_given?
-
ctx.parse_with self
-
end
-
-
###
-
# Parse a file with +filename+
-
1
def parse_file filename, encoding = 'UTF-8'
-
raise ArgumentError unless filename
-
raise Errno::ENOENT unless File.exists?(filename)
-
raise Errno::EISDIR if File.directory?(filename)
-
ctx = ParserContext.file(filename, encoding)
-
yield ctx if block_given?
-
ctx.parse_with self
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module HTML
-
1
module SAX
-
###
-
# Context for HTML SAX parsers. This class is usually not instantiated
-
# by the user. Instead, you should be looking at
-
# Nokogiri::HTML::SAX::Parser
-
1
class ParserContext < Nokogiri::XML::SAX::ParserContext
-
1
def self.new thing, encoding = 'UTF-8'
-
[:read, :close].all? { |x| thing.respond_to?(x) } ? super :
-
memory(thing, encoding)
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module HTML
-
1
module SAX
-
1
class PushParser
-
1
def initialize(doc = XML::SAX::Document.new, file_name = nil, encoding = 'UTF-8')
-
@document = doc
-
@encoding = encoding
-
@sax_parser = HTML::SAX::Parser.new(doc, @encoding)
-
-
## Create our push parser context
-
initialize_native(@sax_parser, file_name, @encoding)
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
class SyntaxError < ::StandardError
-
end
-
end
-
1
module Nokogiri
-
# The version of Nokogiri you are using
-
1
VERSION = '1.5.5'
-
-
1
class VersionInfo # :nodoc:
-
1
def jruby?
-
2
::JRUBY_VERSION if RUBY_PLATFORM == "java"
-
end
-
-
1
def engine
-
1
defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'mri'
-
end
-
-
1
def loaded_parser_version
-
3
LIBXML_PARSER_VERSION.scan(/^(.*)(..)(..)$/).first.collect{ |j|
-
9
j.to_i
-
}.join(".")
-
end
-
-
1
def compiled_parser_version
-
3
LIBXML_VERSION
-
end
-
-
1
def libxml2?
-
3
defined?(LIBXML_VERSION)
-
end
-
-
1
def warnings
-
2
return [] unless libxml2?
-
-
2
if compiled_parser_version != loaded_parser_version
-
["Nokogiri was built against LibXML version #{compiled_parser_version}, but has dynamically loaded #{loaded_parser_version}"]
-
else
-
2
[]
-
end
-
end
-
-
1
def to_hash
-
1
hash_info = {}
-
1
hash_info['warnings'] = []
-
1
hash_info['nokogiri'] = Nokogiri::VERSION
-
1
hash_info['ruby'] = {}
-
1
hash_info['ruby']['version'] = ::RUBY_VERSION
-
1
hash_info['ruby']['platform'] = ::RUBY_PLATFORM
-
1
hash_info['ruby']['description'] = ::RUBY_DESCRIPTION
-
1
hash_info['ruby']['engine'] = engine
-
1
hash_info['ruby']['jruby'] = jruby? if jruby?
-
-
1
if libxml2?
-
1
hash_info['libxml'] = {}
-
1
hash_info['libxml']['binding'] = 'extension'
-
1
hash_info['libxml']['compiled'] = compiled_parser_version
-
1
hash_info['libxml']['loaded'] = loaded_parser_version
-
1
hash_info['warnings'] = warnings
-
end
-
-
1
hash_info
-
end
-
-
1
def to_markdown
-
begin
-
require 'psych'
-
rescue LoadError
-
end
-
require 'yaml'
-
"# Nokogiri (#{Nokogiri::VERSION})\n" +
-
YAML.dump(to_hash).each_line.map { |line| " #{line}" }.join
-
end
-
-
# FIXME: maybe switch to singleton?
-
1
@@instance = new
-
1
@@instance.warnings.each do |warning|
-
warn "WARNING: #{warning}"
-
end
-
3
def self.instance; @@instance; end
-
end
-
-
# More complete version information about libxml
-
1
VERSION_INFO = VersionInfo.instance.to_hash
-
-
1
def self.uses_libxml? # :nodoc:
-
VersionInfo.instance.libxml2?
-
end
-
-
1
def self.jruby? # :nodoc:
-
1
VersionInfo.instance.jruby?
-
end
-
end
-
1
require 'nokogiri/xml/pp'
-
1
require 'nokogiri/xml/parse_options'
-
1
require 'nokogiri/xml/sax'
-
1
require 'nokogiri/xml/node'
-
1
require 'nokogiri/xml/attribute_decl'
-
1
require 'nokogiri/xml/element_decl'
-
1
require 'nokogiri/xml/element_content'
-
1
require 'nokogiri/xml/character_data'
-
1
require 'nokogiri/xml/namespace'
-
1
require 'nokogiri/xml/attr'
-
1
require 'nokogiri/xml/dtd'
-
1
require 'nokogiri/xml/cdata'
-
1
require 'nokogiri/xml/text'
-
1
require 'nokogiri/xml/document'
-
1
require 'nokogiri/xml/document_fragment'
-
1
require 'nokogiri/xml/processing_instruction'
-
1
require 'nokogiri/xml/node_set'
-
1
require 'nokogiri/xml/syntax_error'
-
1
require 'nokogiri/xml/xpath'
-
1
require 'nokogiri/xml/xpath_context'
-
1
require 'nokogiri/xml/builder'
-
1
require 'nokogiri/xml/reader'
-
1
require 'nokogiri/xml/notation'
-
1
require 'nokogiri/xml/entity_decl'
-
1
require 'nokogiri/xml/schema'
-
1
require 'nokogiri/xml/relax_ng'
-
-
1
module Nokogiri
-
1
class << self
-
###
-
# Parse XML. Convenience method for Nokogiri::XML::Document.parse
-
1
def XML thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_XML, &block
-
17
Nokogiri::XML::Document.parse(thing, url, encoding, options, &block)
-
end
-
end
-
-
1
module XML
-
# Original C14N 1.0 spec canonicalization
-
1
XML_C14N_1_0 = 0
-
# Exclusive C14N 1.0 spec canonicalization
-
1
XML_C14N_EXCLUSIVE_1_0 = 1
-
# C14N 1.1 spec canonicalization
-
1
XML_C14N_1_1 = 2
-
1
class << self
-
###
-
# Parse an XML document using the Nokogiri::XML::Reader API. See
-
# Nokogiri::XML::Reader for mor information
-
1
def Reader string_or_io, url = nil, encoding = nil, options = ParseOptions::STRICT
-
-
options = Nokogiri::XML::ParseOptions.new(options) if Fixnum === options
-
# Give the options to the user
-
yield options if block_given?
-
-
if string_or_io.respond_to? :read
-
return Reader.from_io(string_or_io, url, encoding, options.to_i)
-
end
-
Reader.from_memory(string_or_io, url, encoding, options.to_i)
-
end
-
-
###
-
# Parse XML. Convenience method for Nokogiri::XML::Document.parse
-
1
def parse thing, url = nil, encoding = nil, options = ParseOptions::DEFAULT_XML, &block
-
Document.parse(thing, url, encoding, options, &block)
-
end
-
-
####
-
# Parse a fragment from +string+ in to a NodeSet.
-
1
def fragment string
-
XML::DocumentFragment.parse(string)
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class Attr < Node
-
1
alias :value :content
-
1
alias :to_s :content
-
1
alias :content= :value=
-
-
1
private
-
1
def inspect_attributes
-
[:name, :namespace, :value]
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
###
-
# Represents an attribute declaration in a DTD
-
1
class AttributeDecl < Nokogiri::XML::Node
-
1
undef_method :attribute_nodes
-
1
undef_method :attributes
-
1
undef_method :content
-
1
undef_method :namespace
-
1
undef_method :namespace_definitions
-
1
undef_method :line if method_defined?(:line)
-
-
1
def inspect
-
"#<#{self.class.name}:#{sprintf("0x%x", object_id)} #{to_s.inspect}>"
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
###
-
# Nokogiri builder can be used for building XML and HTML documents.
-
#
-
# == Synopsis:
-
#
-
# builder = Nokogiri::XML::Builder.new do |xml|
-
# xml.root {
-
# xml.products {
-
# xml.widget {
-
# xml.id_ "10"
-
# xml.name "Awesome widget"
-
# }
-
# }
-
# }
-
# end
-
# puts builder.to_xml
-
#
-
# Will output:
-
#
-
# <?xml version="1.0"?>
-
# <root>
-
# <products>
-
# <widget>
-
# <id>10</id>
-
# <name>Awesome widget</name>
-
# </widget>
-
# </products>
-
# </root>
-
#
-
#
-
# === Builder scope
-
#
-
# The builder allows two forms. When the builder is supplied with a block
-
# that has a parameter, the outside scope is maintained. This means you
-
# can access variables that are outside your builder. If you don't need
-
# outside scope, you can use the builder without the "xml" prefix like
-
# this:
-
#
-
# builder = Nokogiri::XML::Builder.new do
-
# root {
-
# products {
-
# widget {
-
# id_ "10"
-
# name "Awesome widget"
-
# }
-
# }
-
# }
-
# end
-
#
-
# == Special Tags
-
#
-
# The builder works by taking advantage of method_missing. Unfortunately
-
# some methods are defined in ruby that are difficult or dangerous to
-
# remove. You may want to create tags with the name "type", "class", and
-
# "id" for example. In that case, you can use an underscore to
-
# disambiguate your tag name from the method call.
-
#
-
# Here is an example of using the underscore to disambiguate tag names from
-
# ruby methods:
-
#
-
# @objects = [Object.new, Object.new, Object.new]
-
#
-
# builder = Nokogiri::XML::Builder.new do |xml|
-
# xml.root {
-
# xml.objects {
-
# @objects.each do |o|
-
# xml.object {
-
# xml.type_ o.type
-
# xml.class_ o.class.name
-
# xml.id_ o.id
-
# }
-
# end
-
# }
-
# }
-
# end
-
# puts builder.to_xml
-
#
-
# The underscore may be used with any tag name, and the last underscore
-
# will just be removed. This code will output the following XML:
-
#
-
# <?xml version="1.0"?>
-
# <root>
-
# <objects>
-
# <object>
-
# <type>Object</type>
-
# <class>Object</class>
-
# <id>48390</id>
-
# </object>
-
# <object>
-
# <type>Object</type>
-
# <class>Object</class>
-
# <id>48380</id>
-
# </object>
-
# <object>
-
# <type>Object</type>
-
# <class>Object</class>
-
# <id>48370</id>
-
# </object>
-
# </objects>
-
# </root>
-
#
-
# == Tag Attributes
-
#
-
# Tag attributes may be supplied as method arguments. Here is our
-
# previous example, but using attributes rather than tags:
-
#
-
# @objects = [Object.new, Object.new, Object.new]
-
#
-
# builder = Nokogiri::XML::Builder.new do |xml|
-
# xml.root {
-
# xml.objects {
-
# @objects.each do |o|
-
# xml.object(:type => o.type, :class => o.class, :id => o.id)
-
# end
-
# }
-
# }
-
# end
-
# puts builder.to_xml
-
#
-
# === Tag Attribute Short Cuts
-
#
-
# A couple attribute short cuts are available when building tags. The
-
# short cuts are available by special method calls when building a tag.
-
#
-
# This example builds an "object" tag with the class attribute "classy"
-
# and the id of "thing":
-
#
-
# builder = Nokogiri::XML::Builder.new do |xml|
-
# xml.root {
-
# xml.objects {
-
# xml.object.classy.thing!
-
# }
-
# }
-
# end
-
# puts builder.to_xml
-
#
-
# Which will output:
-
#
-
# <?xml version="1.0"?>
-
# <root>
-
# <objects>
-
# <object class="classy" id="thing"/>
-
# </objects>
-
# </root>
-
#
-
# All other options are still supported with this syntax, including
-
# blocks and extra tag attributes.
-
#
-
# == Namespaces
-
#
-
# Namespaces are added similarly to attributes. Nokogiri::XML::Builder
-
# assumes that when an attribute starts with "xmlns", it is meant to be
-
# a namespace:
-
#
-
# builder = Nokogiri::XML::Builder.new { |xml|
-
# xml.root('xmlns' => 'default', 'xmlns:foo' => 'bar') do
-
# xml.tenderlove
-
# end
-
# }
-
# puts builder.to_xml
-
#
-
# Will output XML like this:
-
#
-
# <?xml version="1.0"?>
-
# <root xmlns:foo="bar" xmlns="default">
-
# <tenderlove/>
-
# </root>
-
#
-
# === Referencing declared namespaces
-
#
-
# Tags that reference non-default namespaces (i.e. a tag "foo:bar") can be
-
# built by using the Nokogiri::XML::Builder#[] method.
-
#
-
# For example:
-
#
-
# builder = Nokogiri::XML::Builder.new do |xml|
-
# xml.root('xmlns:foo' => 'bar') {
-
# xml.objects {
-
# xml['foo'].object.classy.thing!
-
# }
-
# }
-
# end
-
# puts builder.to_xml
-
#
-
# Will output this XML:
-
#
-
# <?xml version="1.0"?>
-
# <root xmlns:foo="bar">
-
# <objects>
-
# <foo:object class="classy" id="thing"/>
-
# </objects>
-
# </root>
-
#
-
# Note the "foo:object" tag.
-
#
-
# == Document Types
-
#
-
# To create a document type (DTD), access use the Builder#doc method to get
-
# the current context document. Then call Node#create_internal_subset to
-
# create the DTD node.
-
#
-
# For example, this Ruby:
-
#
-
# builder = Nokogiri::XML::Builder.new do |xml|
-
# xml.doc.create_internal_subset(
-
# 'html',
-
# "-//W3C//DTD HTML 4.01 Transitional//EN",
-
# "http://www.w3.org/TR/html4/loose.dtd"
-
# )
-
# xml.root do
-
# xml.foo
-
# end
-
# end
-
#
-
# puts builder.to_xml
-
#
-
# Will output this xml:
-
#
-
# <?xml version="1.0"?>
-
# <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
-
# <root>
-
# <foo/>
-
# </root>
-
#
-
1
class Builder
-
# The current Document object being built
-
1
attr_accessor :doc
-
-
# The parent of the current node being built
-
1
attr_accessor :parent
-
-
# A context object for use when the block has no arguments
-
1
attr_accessor :context
-
-
1
attr_accessor :arity # :nodoc:
-
-
###
-
# Create a builder with an existing root object. This is for use when
-
# you have an existing document that you would like to augment with
-
# builder methods. The builder context created will start with the
-
# given +root+ node.
-
#
-
# For example:
-
#
-
# doc = Nokogiri::XML(open('somedoc.xml'))
-
# Nokogiri::XML::Builder.with(doc.at('some_tag')) do |xml|
-
# # ... Use normal builder methods here ...
-
# xml.awesome # add the "awesome" tag below "some_tag"
-
# end
-
#
-
1
def self.with root, &block
-
new({}, root, &block)
-
end
-
-
###
-
# Create a new Builder object. +options+ are sent to the top level
-
# Document that is being built.
-
#
-
# Building a document with a particular encoding for example:
-
#
-
# Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
-
# ...
-
# end
-
1
def initialize options = {}, root = nil, &block
-
-
if root
-
@doc = root.document
-
@parent = root
-
else
-
namespace = self.class.name.split('::')
-
namespace[-1] = 'Document'
-
@doc = eval(namespace.join('::')).new
-
@parent = @doc
-
end
-
-
@context = nil
-
@arity = nil
-
@ns = nil
-
-
options.each do |k,v|
-
@doc.send(:"#{k}=", v)
-
end
-
-
return unless block_given?
-
-
@arity = block.arity
-
if @arity <= 0
-
@context = eval('self', block.binding)
-
instance_eval(&block)
-
else
-
yield self
-
end
-
-
@parent = @doc
-
end
-
-
###
-
# Create a Text Node with content of +string+
-
1
def text string
-
insert @doc.create_text_node(string)
-
end
-
-
###
-
# Create a CDATA Node with content of +string+
-
1
def cdata string
-
insert doc.create_cdata(string)
-
end
-
-
###
-
# Create a Comment Node with content of +string+
-
1
def comment string
-
insert doc.create_comment(string)
-
end
-
-
###
-
# Build a tag that is associated with namespace +ns+. Raises an
-
# ArgumentError if +ns+ has not been defined higher in the tree.
-
1
def [] ns
-
@ns = @parent.namespace_definitions.find { |x| x.prefix == ns.to_s }
-
return self if @ns
-
-
@parent.ancestors.each do |a|
-
next if a == doc
-
@ns = a.namespace_definitions.find { |x| x.prefix == ns.to_s }
-
return self if @ns
-
end
-
-
raise ArgumentError, "Namespace #{ns} has not been defined"
-
end
-
-
###
-
# Convert this Builder object to XML
-
1
def to_xml(*args)
-
if Nokogiri.jruby?
-
options = args.first.is_a?(Hash) ? args.shift : {}
-
if !options[:save_with]
-
options[:save_with] = Node::SaveOptions::AS_BUILDER
-
end
-
args.insert(0, options)
-
end
-
@doc.to_xml(*args)
-
end
-
-
###
-
# Append the given raw XML +string+ to the document
-
1
def << string
-
@doc.fragment(string).children.each { |x| insert(x) }
-
end
-
-
1
def method_missing method, *args, &block # :nodoc:
-
if @context && @context.respond_to?(method)
-
@context.send(method, *args, &block)
-
else
-
node = @doc.create_element(method.to_s.sub(/[_!]$/, ''),*args) { |n|
-
# Set up the namespace
-
if @ns
-
n.namespace = @ns
-
@ns = nil
-
end
-
}
-
insert(node, &block)
-
end
-
end
-
-
1
private
-
###
-
# Insert +node+ as a child of the current Node
-
1
def insert(node, &block)
-
node.parent = @parent
-
if block_given?
-
old_parent = @parent
-
@parent = node
-
@arity ||= block.arity
-
if @arity <= 0
-
instance_eval(&block)
-
else
-
block.call(self)
-
end
-
@parent = old_parent
-
end
-
NodeBuilder.new(node, self)
-
end
-
-
1
class NodeBuilder # :nodoc:
-
1
def initialize node, doc_builder
-
@node = node
-
@doc_builder = doc_builder
-
end
-
-
1
def []= k, v
-
@node[k] = v
-
end
-
-
1
def [] k
-
@node[k]
-
end
-
-
1
def method_missing(method, *args, &block)
-
opts = args.last.is_a?(Hash) ? args.pop : {}
-
case method.to_s
-
when /^(.*)!$/
-
@node['id'] = $1
-
@node.content = args.first if args.first
-
when /^(.*)=/
-
@node[$1] = args.first
-
else
-
@node['class'] =
-
((@node['class'] || '').split(/\s/) + [method.to_s]).join(' ')
-
@node.content = args.first if args.first
-
end
-
-
# Assign any extra options
-
opts.each do |k,v|
-
@node[k.to_s] = ((@node[k.to_s] || '').split(/\s/) + [v]).join(' ')
-
end
-
-
if block_given?
-
old_parent = @doc_builder.parent
-
@doc_builder.parent = @node
-
value = @doc_builder.instance_eval(&block)
-
@doc_builder.parent = old_parent
-
return value
-
end
-
self
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class CDATA < Nokogiri::XML::Text
-
###
-
# Get the name of this CDATA node
-
1
def name
-
'#cdata-section'
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class CharacterData < Nokogiri::XML::Node
-
1
include Nokogiri::XML::PP::CharacterData
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
##
-
# Nokogiri::XML::Document is the main entry point for dealing with
-
# XML documents. The Document is created by parsing an XML document.
-
# See Nokogiri::XML::Document.parse() for more information on parsing.
-
#
-
# For searching a Document, see Nokogiri::XML::Node#css and
-
# Nokogiri::XML::Node#xpath
-
#
-
1
class Document < Nokogiri::XML::Node
-
# I'm ignoring unicode characters here.
-
# See http://www.w3.org/TR/REC-xml-names/#ns-decl for more details.
-
1
NCNAME_START_CHAR = "A-Za-z_"
-
1
NCNAME_CHAR = NCNAME_START_CHAR + "\\-.0-9"
-
1
NCNAME_RE = /^xmlns(:[#{NCNAME_START_CHAR}][#{NCNAME_CHAR}]*)?$/
-
-
##
-
# Parse an XML file.
-
#
-
# +string_or_io+ may be a String, or any object that responds to
-
# _read_ and _close_ such as an IO, or StringIO.
-
#
-
# +url+ (optional) is the URI where this document is located.
-
#
-
# +encoding+ (optional) is the encoding that should be used when processing
-
# the document.
-
#
-
# +options+ (optional) is a configuration object that sets options during
-
# parsing, such as Nokogiri::XML::ParseOptions::RECOVER. See the
-
# Nokogiri::XML::ParseOptions for more information.
-
#
-
# +block+ (optional) is passed a configuration object on which
-
# parse options may be set.
-
#
-
# When parsing untrusted documents, it's recommended that the
-
# +nonet+ option be used, as shown in this example code:
-
#
-
# Nokogiri::XML::Document.parse(xml_string) { |config| config.nonet }
-
#
-
# Nokogiri.XML() is a convenience method which will call this method.
-
#
-
1
def self.parse string_or_io, url = nil, encoding = nil, options = ParseOptions::DEFAULT_XML, &block
-
17
options = Nokogiri::XML::ParseOptions.new(options) if Fixnum === options
-
# Give the options to the user
-
17
yield options if block_given?
-
-
17
doc = if string_or_io.respond_to?(:read)
-
17
url ||= string_or_io.respond_to?(:path) ? string_or_io.path : nil
-
17
read_io(string_or_io, url, encoding, options.to_i)
-
else
-
# read_memory pukes on empty docs
-
return new if string_or_io.nil? or string_or_io.empty?
-
read_memory(string_or_io, url, encoding, options.to_i)
-
end
-
-
# do xinclude processing
-
17
doc.do_xinclude(options) if options.xinclude?
-
-
17
return doc
-
end
-
-
# A list of Nokogiri::XML::SyntaxError found when parsing a document
-
1
attr_accessor :errors
-
-
1
def initialize *args # :nodoc:
-
17
@errors = []
-
17
@decorators = nil
-
end
-
-
##
-
# Create an element with +name+, and optionally setting the content and attributes.
-
#
-
# doc.create_element "div" # <div></div>
-
# doc.create_element "div", :class => "container" # <div class='container'></div>
-
# doc.create_element "div", "contents" # <div>contents</div>
-
# doc.create_element "div", "contents", :class => "container" # <div class='container'>contents</div>
-
# doc.create_element "div" { |node| node['class'] = "container" } # <div class='container'></div>
-
#
-
1
def create_element name, *args, &block
-
elm = Nokogiri::XML::Element.new(name, self, &block)
-
args.each do |arg|
-
case arg
-
when Hash
-
arg.each { |k,v|
-
key = k.to_s
-
if key =~ NCNAME_RE
-
ns_name = key.split(":", 2)[1]
-
elm.add_namespace_definition ns_name, v
-
next
-
end
-
elm[k.to_s] = v.to_s
-
}
-
else
-
elm.content = arg
-
end
-
end
-
elm
-
end
-
-
# Create a Text Node with +string+
-
1
def create_text_node string, &block
-
Nokogiri::XML::Text.new string.to_s, self, &block
-
end
-
-
# Create a CDATA Node containing +string+
-
1
def create_cdata string, &block
-
Nokogiri::XML::CDATA.new self, string.to_s, &block
-
end
-
-
# Create a Comment Node containing +string+
-
1
def create_comment string, &block
-
Nokogiri::XML::Comment.new self, string.to_s, &block
-
end
-
-
# The name of this document. Always returns "document"
-
1
def name
-
'document'
-
end
-
-
# A reference to +self+
-
1
def document
-
self
-
end
-
-
##
-
# Recursively get all namespaces from this node and its subtree and
-
# return them as a hash.
-
#
-
# For example, given this document:
-
#
-
# <root xmlns:foo="bar">
-
# <bar xmlns:hello="world" />
-
# </root>
-
#
-
# This method will return:
-
#
-
# { 'xmlns:foo' => 'bar', 'xmlns:hello' => 'world' }
-
#
-
# WARNING: this method will clobber duplicate names in the keys.
-
# For example, given this document:
-
#
-
# <root xmlns:foo="bar">
-
# <bar xmlns:foo="baz" />
-
# </root>
-
#
-
# The hash returned will look like this: { 'xmlns:foo' => 'bar' }
-
#
-
# Non-prefixed default namespaces (as in "xmlns=") are not included
-
# in the hash.
-
#
-
# Note this is a very expensive operation in current implementation, as it
-
# traverses the entire graph, and also has to bring each node across the
-
# libxml bridge into a ruby object.
-
1
def collect_namespaces
-
ns = {}
-
traverse { |j| ns.merge!(j.namespaces) }
-
ns
-
end
-
-
# Get the list of decorators given +key+
-
1
def decorators key
-
@decorators ||= Hash.new
-
@decorators[key] ||= []
-
end
-
-
##
-
# Validate this Document against it's DTD. Returns a list of errors on
-
# the document or +nil+ when there is no DTD.
-
1
def validate
-
return nil unless internal_subset
-
internal_subset.validate self
-
end
-
-
##
-
# Explore a document with shortcut methods. See Nokogiri::Slop for details.
-
#
-
# Note that any nodes that have been instantiated before #slop!
-
# is called will not be decorated with sloppy behavior. So, if you're in
-
# irb, the preferred idiom is:
-
#
-
# irb> doc = Nokogiri::Slop my_markup
-
#
-
# and not
-
#
-
# irb> doc = Nokogiri::HTML my_markup
-
# ... followed by irb's implicit inspect (and therefore instantiation of every node) ...
-
# irb> doc.slop!
-
# ... which does absolutely nothing.
-
#
-
1
def slop!
-
unless decorators(XML::Node).include? Nokogiri::Decorators::Slop
-
decorators(XML::Node) << Nokogiri::Decorators::Slop
-
decorate!
-
end
-
-
self
-
end
-
-
##
-
# Apply any decorators to +node+
-
1
def decorate node
-
130
return unless @decorators
-
@decorators.each { |klass,list|
-
next unless node.is_a?(klass)
-
list.each { |moodule| node.extend(moodule) }
-
}
-
end
-
-
1
alias :to_xml :serialize
-
1
alias :clone :dup
-
-
# Get the hash of namespaces on the root Nokogiri::XML::Node
-
1
def namespaces
-
root ? root.namespaces : {}
-
end
-
-
##
-
# Create a Nokogiri::XML::DocumentFragment from +tags+
-
# Returns an empty fragment if +tags+ is nil.
-
1
def fragment tags = nil
-
DocumentFragment.new(self, tags, self.root)
-
end
-
-
1
undef_method :swap, :parent, :namespace, :default_namespace=
-
1
undef_method :add_namespace_definition, :attributes
-
1
undef_method :namespace_definitions, :line, :add_namespace
-
-
1
def add_child node_or_tags
-
raise "Document already has a root node" if root
-
node_or_tags = coerce(node_or_tags)
-
if node_or_tags.is_a?(XML::NodeSet)
-
raise "Document cannot have multiple root nodes" if node_or_tags.size > 1
-
super(node_or_tags.first)
-
else
-
super
-
end
-
end
-
1
alias :<< :add_child
-
-
##
-
# +JRuby+
-
# Wraps Java's org.w3c.dom.document and returns Nokogiri::XML::Document
-
1
def self.wrap document
-
raise "JRuby only method" unless Nokogiri.jruby?
-
return wrapJavaDocument(document)
-
end
-
-
##
-
# +JRuby+
-
# Returns Java's org.w3c.dom.document of this Document.
-
1
def to_java
-
raise "JRuby only method" unless Nokogiri.jruby?
-
return toJavaDocument()
-
end
-
-
1
private
-
1
def implied_xpath_context
-
"/"
-
end
-
-
1
def inspect_attributes
-
[:name, :children]
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class DTD < Nokogiri::XML::Node
-
1
undef_method :attribute_nodes
-
1
undef_method :values
-
1
undef_method :content
-
1
undef_method :namespace
-
1
undef_method :namespace_definitions
-
1
undef_method :line if method_defined?(:line)
-
-
1
def keys
-
attributes.keys
-
end
-
-
1
def each &block
-
attributes.each { |key, value|
-
block.call([key, value])
-
}
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
###
-
# Represents the allowed content in an Element Declaration inside a DTD:
-
#
-
# <?xml version="1.0"?><?TEST-STYLE PIDATA?>
-
# <!DOCTYPE staff SYSTEM "staff.dtd" [
-
# <!ELEMENT div1 (head, (p | list | note)*, div2*)>
-
# ]>
-
# </root>
-
#
-
# ElementContent represents the tree inside the <!ELEMENT> tag shown above
-
# that lists the possible content for the div1 tag.
-
1
class ElementContent
-
# Possible definitions of type
-
1
PCDATA = 1
-
1
ELEMENT = 2
-
1
SEQ = 3
-
1
OR = 4
-
-
# Possible content occurrences
-
1
ONCE = 1
-
1
OPT = 2
-
1
MULT = 3
-
1
PLUS = 4
-
-
1
attr_reader :document
-
-
###
-
# Get the children of this ElementContent node
-
1
def children
-
[c1, c2].compact
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class ElementDecl < Nokogiri::XML::Node
-
1
undef_method :namespace
-
1
undef_method :namespace_definitions
-
1
undef_method :line if method_defined?(:line)
-
-
1
def inspect
-
"#<#{self.class.name}:#{sprintf("0x%x", object_id)} #{to_s.inspect}>"
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class EntityDecl < Nokogiri::XML::Node
-
1
undef_method :attribute_nodes
-
1
undef_method :attributes
-
1
undef_method :namespace
-
1
undef_method :namespace_definitions
-
1
undef_method :line if method_defined?(:line)
-
-
1
def self.new name, doc, *args
-
doc.create_entity(name, *args)
-
end
-
-
1
def inspect
-
"#<#{self.class.name}:#{sprintf("0x%x", object_id)} #{to_s.inspect}>"
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class Namespace
-
1
include Nokogiri::XML::PP::Node
-
1
attr_reader :document
-
-
1
private
-
1
def inspect_attributes
-
[:prefix, :href]
-
end
-
end
-
end
-
end
-
1
require 'stringio'
-
1
require 'nokogiri/xml/node/save_options'
-
-
1
module Nokogiri
-
1
module XML
-
####
-
# Nokogiri::XML::Node is your window to the fun filled world of dealing
-
# with XML and HTML tags. A Nokogiri::XML::Node may be treated similarly
-
# to a hash with regard to attributes. For example (from irb):
-
#
-
# irb(main):004:0> node
-
# => <a href="#foo" id="link">link</a>
-
# irb(main):005:0> node['href']
-
# => "#foo"
-
# irb(main):006:0> node.keys
-
# => ["href", "id"]
-
# irb(main):007:0> node.values
-
# => ["#foo", "link"]
-
# irb(main):008:0> node['class'] = 'green'
-
# => "green"
-
# irb(main):009:0> node
-
# => <a href="#foo" id="link" class="green">link</a>
-
# irb(main):010:0>
-
#
-
# See Nokogiri::XML::Node#[] and Nokogiri::XML#[]= for more information.
-
#
-
# Nokogiri::XML::Node also has methods that let you move around your
-
# tree. For navigating your tree, see:
-
#
-
# * Nokogiri::XML::Node#parent
-
# * Nokogiri::XML::Node#children
-
# * Nokogiri::XML::Node#next
-
# * Nokogiri::XML::Node#previous
-
#
-
# You may search this node's subtree using Node#xpath and Node#css
-
1
class Node
-
1
include Nokogiri::XML::PP::Node
-
1
include Enumerable
-
-
# Element node type, see Nokogiri::XML::Node#element?
-
1
ELEMENT_NODE = 1
-
# Attribute node type
-
1
ATTRIBUTE_NODE = 2
-
# Text node type, see Nokogiri::XML::Node#text?
-
1
TEXT_NODE = 3
-
# CDATA node type, see Nokogiri::XML::Node#cdata?
-
1
CDATA_SECTION_NODE = 4
-
# Entity reference node type
-
1
ENTITY_REF_NODE = 5
-
# Entity node type
-
1
ENTITY_NODE = 6
-
# PI node type
-
1
PI_NODE = 7
-
# Comment node type, see Nokogiri::XML::Node#comment?
-
1
COMMENT_NODE = 8
-
# Document node type, see Nokogiri::XML::Node#xml?
-
1
DOCUMENT_NODE = 9
-
# Document type node type
-
1
DOCUMENT_TYPE_NODE = 10
-
# Document fragment node type
-
1
DOCUMENT_FRAG_NODE = 11
-
# Notation node type
-
1
NOTATION_NODE = 12
-
# HTML document node type, see Nokogiri::XML::Node#html?
-
1
HTML_DOCUMENT_NODE = 13
-
# DTD node type
-
1
DTD_NODE = 14
-
# Element declaration type
-
1
ELEMENT_DECL = 15
-
# Attribute declaration type
-
1
ATTRIBUTE_DECL = 16
-
# Entity declaration type
-
1
ENTITY_DECL = 17
-
# Namespace declaration type
-
1
NAMESPACE_DECL = 18
-
# XInclude start type
-
1
XINCLUDE_START = 19
-
# XInclude end type
-
1
XINCLUDE_END = 20
-
# DOCB document node type
-
1
DOCB_DOCUMENT_NODE = 21
-
-
1
def initialize name, document # :nodoc:
-
# ... Ya. This is empty on purpose.
-
end
-
-
###
-
# Decorate this node with the decorators set up in this node's Document
-
1
def decorate!
-
document.decorate(self)
-
end
-
-
###
-
# Search this node for +paths+. +paths+ can be XPath or CSS, and an
-
# optional hash of namespaces may be appended.
-
# See Node#xpath and Node#css.
-
1
def search *paths
-
# TODO use paths, handler, ns, binds = extract_params(paths)
-
ns = paths.last.is_a?(Hash) ? paths.pop :
-
(document.root ? document.root.namespaces : {})
-
-
prefix = "#{implied_xpath_context}/"
-
-
xpath(*(paths.map { |path|
-
path = path.to_s
-
path =~ /^(\.\/|\/|\.\.|\.$)/ ? path : CSS.xpath_for(
-
path,
-
:prefix => prefix,
-
:ns => ns
-
)
-
}.flatten.uniq) + [ns])
-
end
-
1
alias :/ :search
-
-
###
-
# call-seq: xpath *paths, [namespace-bindings, variable-bindings, custom-handler-class]
-
#
-
# Search this node for XPath +paths+. +paths+ must be one or more XPath
-
# queries.
-
#
-
# node.xpath('.//title')
-
#
-
# A hash of namespace bindings may be appended. For example:
-
#
-
# node.xpath('.//foo:name', {'foo' => 'http://example.org/'})
-
# node.xpath('.//xmlns:name', node.root.namespaces)
-
#
-
# A hash of variable bindings may also be appended to the namespace bindings. For example:
-
#
-
# node.xpath('.//address[@domestic=$value]', nil, {:value => 'Yes'})
-
#
-
# Custom XPath functions may also be defined. To define custom
-
# functions create a class and implement the function you want
-
# to define. The first argument to the method will be the
-
# current matching NodeSet. Any other arguments are ones that
-
# you pass in. Note that this class may appear anywhere in the
-
# argument list. For example:
-
#
-
# node.xpath('.//title[regex(., "\w+")]', Class.new {
-
# def regex node_set, regex
-
# node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
-
# end
-
# }.new)
-
#
-
1
def xpath *paths
-
return NodeSet.new(document) unless document
-
-
paths, handler, ns, binds = extract_params(paths)
-
-
sets = paths.map { |path|
-
ctx = XPathContext.new(self)
-
ctx.register_namespaces(ns)
-
path = path.gsub(/xmlns:/, ' :') unless Nokogiri.uses_libxml?
-
-
binds.each do |key,value|
-
ctx.register_variable key.to_s, value
-
end if binds
-
-
ctx.evaluate(path, handler)
-
}
-
return sets.first if sets.length == 1
-
-
NodeSet.new(document) do |combined|
-
sets.each do |set|
-
set.each do |node|
-
combined << node
-
end
-
end
-
end
-
end
-
-
###
-
# call-seq: css *rules, [namespace-bindings, custom-pseudo-class]
-
#
-
# Search this node for CSS +rules+. +rules+ must be one or more CSS
-
# selectors. For example:
-
#
-
# node.css('title')
-
# node.css('body h1.bold')
-
# node.css('div + p.green', 'div#one')
-
#
-
# A hash of namespace bindings may be appended. For example:
-
#
-
# node.css('bike|tire', {'bike' => 'http://schwinn.com/'})
-
#
-
# Custom CSS pseudo classes may also be defined. To define
-
# custom pseudo classes, create a class and implement the custom
-
# pseudo class you want defined. The first argument to the
-
# method will be the current matching NodeSet. Any other
-
# arguments are ones that you pass in. For example:
-
#
-
# node.css('title:regex("\w+")', Class.new {
-
# def regex node_set, regex
-
# node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
-
# end
-
# }.new)
-
#
-
# Note that the CSS query string is case-sensitive with regards
-
# to your document type. That is, if you're looking for "H1" in
-
# an HTML document, you'll never find anything, since HTML tags
-
# will match only lowercase CSS queries. However, "H1" might be
-
# found in an XML document, where tags names are case-sensitive
-
# (e.g., "H1" is distinct from "h1").
-
#
-
1
def css *rules
-
rules, handler, ns, binds = extract_params(rules)
-
-
prefix = "#{implied_xpath_context}/"
-
-
rules = rules.map { |rule|
-
CSS.xpath_for(rule, :prefix => prefix, :ns => ns)
-
}.flatten.uniq + [ns, handler, binds].compact
-
-
xpath(*rules)
-
end
-
-
###
-
# Search this node's immediate children using CSS selector +selector+
-
1
def > selector
-
ns = document.root.namespaces
-
xpath CSS.xpath_for(selector, :prefix => "./", :ns => ns).first
-
end
-
-
###
-
# Search for the first occurrence of +path+.
-
#
-
# Returns nil if nothing is found, otherwise a Node.
-
1
def at path, ns = document.root ? document.root.namespaces : {}
-
search(path, ns).first
-
end
-
1
alias :% :at
-
-
##
-
# Search this node for the first occurrence of XPath +paths+.
-
# Equivalent to <tt>xpath(paths).first</tt>
-
# See Node#xpath for more information.
-
#
-
1
def at_xpath *paths
-
xpath(*paths).first
-
end
-
-
##
-
# Search this node for the first occurrence of CSS +rules+.
-
# Equivalent to <tt>css(rules).first</tt>
-
# See Node#css for more information.
-
#
-
1
def at_css *rules
-
css(*rules).first
-
end
-
-
###
-
# Get the attribute value for the attribute +name+
-
1
def [] name
-
return nil unless key?(name.to_s)
-
get(name.to_s)
-
end
-
-
###
-
# Set the attribute value for the attribute +name+ to +value+
-
1
def []= name, value
-
set name.to_s, value
-
end
-
-
###
-
# Add +node_or_tags+ as a child of this Node.
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
-
#
-
# Also see related method +<<+.
-
1
def add_child node_or_tags
-
node_or_tags = coerce(node_or_tags)
-
if node_or_tags.is_a?(XML::NodeSet)
-
node_or_tags.each { |n| add_child_node n }
-
else
-
add_child_node node_or_tags
-
end
-
node_or_tags
-
end
-
-
###
-
# Add +node_or_tags+ as a child of this Node.
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns self, to support chaining of calls (e.g., root << child1 << child2)
-
#
-
# Also see related method +add_child+.
-
1
def << node_or_tags
-
add_child node_or_tags
-
self
-
end
-
###
-
# Insert +node_or_tags+ before this Node (as a sibling).
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
-
#
-
# Also see related method +before+.
-
1
def add_previous_sibling node_or_tags
-
raise ArgumentError.new("A document may not have multiple root nodes.") if parent.is_a?(XML::Document) && !node_or_tags.is_a?(XML::ProcessingInstruction)
-
-
node_or_tags = coerce(node_or_tags)
-
if node_or_tags.is_a?(XML::NodeSet)
-
if text?
-
pivot = Nokogiri::XML::Node.new 'dummy', document
-
add_previous_sibling_node pivot
-
else
-
pivot = self
-
end
-
node_or_tags.each { |n| pivot.send :add_previous_sibling_node, n }
-
pivot.unlink if text?
-
else
-
add_previous_sibling_node node_or_tags
-
end
-
node_or_tags
-
end
-
-
###
-
# Insert +node_or_tags+ after this Node (as a sibling).
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
-
#
-
# Also see related method +after+.
-
1
def add_next_sibling node_or_tags
-
raise ArgumentError.new("A document may not have multiple root nodes.") if parent.is_a?(XML::Document)
-
-
node_or_tags = coerce(node_or_tags)
-
if node_or_tags.is_a?(XML::NodeSet)
-
if text?
-
pivot = Nokogiri::XML::Node.new 'dummy', document
-
add_next_sibling_node pivot
-
else
-
pivot = self
-
end
-
node_or_tags.reverse_each { |n| pivot.send :add_next_sibling_node, n }
-
pivot.unlink if text?
-
else
-
add_next_sibling_node node_or_tags
-
end
-
node_or_tags
-
end
-
-
####
-
# Insert +node_or_tags+ before this node (as a sibling).
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns self, to support chaining of calls.
-
#
-
# Also see related method +add_previous_sibling+.
-
1
def before node_or_tags
-
add_previous_sibling node_or_tags
-
self
-
end
-
-
####
-
# Insert +node_or_tags+ after this node (as a sibling).
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a string containing markup.
-
#
-
# Returns self, to support chaining of calls.
-
#
-
# Also see related method +add_next_sibling+.
-
1
def after node_or_tags
-
add_next_sibling node_or_tags
-
self
-
end
-
-
####
-
# Set the inner html for this Node to +node_or_tags+
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a string containing markup.
-
#
-
# Returns self.
-
#
-
# Also see related method +children=+
-
1
def inner_html= node_or_tags
-
self.children = node_or_tags
-
self
-
end
-
-
####
-
# Set the inner html for this Node +node_or_tags+
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a string containing markup.
-
#
-
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
-
#
-
# Also see related method +inner_html=+
-
1
def children= node_or_tags
-
node_or_tags = coerce(node_or_tags)
-
children.unlink
-
if node_or_tags.is_a?(XML::NodeSet)
-
node_or_tags.each { |n| add_child_node n }
-
else
-
add_child_node node_or_tags
-
end
-
node_or_tags
-
end
-
-
####
-
# Replace this Node with +node_or_tags+.
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
-
#
-
# Also see related method +swap+.
-
1
def replace node_or_tags
-
node_or_tags = coerce(node_or_tags)
-
if node_or_tags.is_a?(XML::NodeSet)
-
if text?
-
replacee = Nokogiri::XML::Node.new 'dummy', document
-
add_previous_sibling_node replacee
-
unlink
-
else
-
replacee = self
-
end
-
node_or_tags.each { |n| replacee.add_previous_sibling n }
-
replacee.unlink
-
else
-
replace_node node_or_tags
-
end
-
node_or_tags
-
end
-
-
####
-
# Swap this Node for +node_or_tags+
-
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
-
#
-
# Returns self, to support chaining of calls.
-
#
-
# Also see related method +replace+.
-
1
def swap node_or_tags
-
replace node_or_tags
-
self
-
end
-
-
1
alias :next :next_sibling
-
1
alias :previous :previous_sibling
-
-
# :stopdoc:
-
# HACK: This is to work around an RDoc bug
-
1
alias :next= :add_next_sibling
-
# :startdoc:
-
-
1
alias :previous= :add_previous_sibling
-
1
alias :remove :unlink
-
1
alias :get_attribute :[]
-
1
alias :attr :[]
-
1
alias :set_attribute :[]=
-
1
alias :text :content
-
1
alias :inner_text :content
-
1
alias :has_attribute? :key?
-
1
alias :name :node_name
-
1
alias :name= :node_name=
-
1
alias :type :node_type
-
1
alias :to_str :text
-
1
alias :clone :dup
-
1
alias :elements :element_children
-
-
####
-
# Returns a hash containing the node's attributes. The key is
-
# the attribute name without any namespace, the value is a Nokogiri::XML::Attr
-
# representing the attribute.
-
# If you need to distinguish attributes with the same name, with different namespaces
-
# use #attribute_nodes instead.
-
1
def attributes
-
Hash[attribute_nodes.map { |node|
-
[node.node_name, node]
-
}]
-
end
-
-
###
-
# Get the attribute values for this Node.
-
1
def values
-
attribute_nodes.map { |node| node.value }
-
end
-
-
###
-
# Get the attribute names for this Node.
-
1
def keys
-
attribute_nodes.map { |node| node.node_name }
-
end
-
-
###
-
# Iterate over each attribute name and value pair for this Node.
-
1
def each
-
attribute_nodes.each { |node|
-
yield [node.node_name, node.value]
-
}
-
end
-
-
###
-
# Remove the attribute named +name+
-
1
def remove_attribute name
-
attributes[name].remove if key? name
-
end
-
1
alias :delete :remove_attribute
-
-
###
-
# Returns true if this Node matches +selector+
-
1
def matches? selector
-
ancestors.last.search(selector).include?(self)
-
end
-
-
###
-
# Create a DocumentFragment containing +tags+ that is relative to _this_
-
# context node.
-
1
def fragment tags
-
type = document.html? ? Nokogiri::HTML : Nokogiri::XML
-
type::DocumentFragment.new(document, tags, self)
-
end
-
-
###
-
# Parse +string_or_io+ as a document fragment within the context of
-
# *this* node. Returns a XML::NodeSet containing the nodes parsed from
-
# +string_or_io+.
-
1
def parse string_or_io, options = nil
-
options ||= (document.html? ? ParseOptions::DEFAULT_HTML : ParseOptions::DEFAULT_XML)
-
if Fixnum === options
-
options = Nokogiri::XML::ParseOptions.new(options)
-
end
-
# Give the options to the user
-
yield options if block_given?
-
-
contents = string_or_io.respond_to?(:read) ?
-
string_or_io.read :
-
string_or_io
-
-
return Nokogiri::XML::NodeSet.new(document) if contents.empty?
-
-
##
-
# This is a horrible hack, but I don't care. See #313 for background.
-
error_count = document.errors.length
-
node_set = in_context(contents, options.to_i)
-
if node_set.empty? and document.errors.length > error_count and options.recover?
-
fragment = Nokogiri::HTML::DocumentFragment.parse contents
-
node_set = fragment.children
-
end
-
node_set
-
end
-
-
####
-
# Set the Node's content to a Text node containing +string+. The string gets XML escaped, not interpreted as markup.
-
1
def content= string
-
self.native_content = encode_special_chars(string.to_s)
-
end
-
-
###
-
# Set the parent Node for this Node
-
1
def parent= parent_node
-
parent_node.add_child(self)
-
parent_node
-
end
-
-
###
-
# Returns a Hash of {prefix => value} for all namespaces on this
-
# node and its ancestors.
-
#
-
# This method returns the same namespaces as #namespace_scopes.
-
#
-
# Returns namespaces in scope for self -- those defined on self
-
# element directly or any ancestor node -- as a Hash of
-
# attribute-name/value pairs. Note that the keys in this hash
-
# XML attributes that would be used to define this namespace,
-
# such as "xmlns:prefix", not just the prefix. Default namespace
-
# set on self will be included with key "xmlns". However,
-
# default namespaces set on ancestor will NOT be, even if self
-
# has no explicit default namespace.
-
1
def namespaces
-
Hash[namespace_scopes.map { |nd|
-
key = ['xmlns', nd.prefix].compact.join(':')
-
if RUBY_VERSION >= '1.9' && document.encoding
-
begin
-
key.force_encoding document.encoding
-
rescue ArgumentError
-
end
-
end
-
[key, nd.href]
-
}]
-
end
-
-
# Returns true if this is a Comment
-
1
def comment?
-
type == COMMENT_NODE
-
end
-
-
# Returns true if this is a CDATA
-
1
def cdata?
-
3
type == CDATA_SECTION_NODE
-
end
-
-
# Returns true if this is an XML::Document node
-
1
def xml?
-
type == DOCUMENT_NODE
-
end
-
-
# Returns true if this is an HTML::Document node
-
1
def html?
-
type == HTML_DOCUMENT_NODE
-
end
-
-
# Returns true if this is a Text node
-
1
def text?
-
50
type == TEXT_NODE
-
end
-
-
# Returns true if this is a DocumentFragment
-
1
def fragment?
-
type == DOCUMENT_FRAG_NODE
-
end
-
-
###
-
# Fetch the Nokogiri::HTML::ElementDescription for this node. Returns
-
# nil on XML documents and on unknown tags.
-
1
def description
-
return nil if document.xml?
-
Nokogiri::HTML::ElementDescription[name]
-
end
-
-
###
-
# Is this a read only node?
-
1
def read_only?
-
# According to gdome2, these are read-only node types
-
[NOTATION_NODE, ENTITY_NODE, ENTITY_DECL].include?(type)
-
end
-
-
# Returns true if this is an Element node
-
1
def element?
-
67
type == ELEMENT_NODE
-
end
-
1
alias :elem? :element?
-
-
###
-
# Turn this node in to a string. If the document is HTML, this method
-
# returns html. If the document is XML, this method returns XML.
-
1
def to_s
-
document.xml? ? to_xml : to_html
-
end
-
-
# Get the inner_html for this node's Node#children
-
1
def inner_html *args
-
children.map { |x| x.to_html(*args) }.join
-
end
-
-
# Get the path to this node as a CSS expression
-
1
def css_path
-
path.split(/\//).map { |part|
-
part.length == 0 ? nil : part.gsub(/\[(\d+)\]/, ':nth-of-type(\1)')
-
}.compact.join(' > ')
-
end
-
-
###
-
# Get a list of ancestor Node for this Node. If +selector+ is given,
-
# the ancestors must match +selector+
-
1
def ancestors selector = nil
-
return NodeSet.new(document) unless respond_to?(:parent)
-
return NodeSet.new(document) unless parent
-
-
parents = [parent]
-
-
while parents.last.respond_to?(:parent)
-
break unless ctx_parent = parents.last.parent
-
parents << ctx_parent
-
end
-
-
return NodeSet.new(document, parents) unless selector
-
-
root = parents.last
-
-
NodeSet.new(document, parents.find_all { |parent|
-
root.search(selector).include?(parent)
-
})
-
end
-
-
###
-
# Adds a default namespace supplied as a string +url+ href, to self.
-
# The consequence is as an xmlns attribute with supplied argument were
-
# present in parsed XML. A default namespace set with this method will
-
# now show up in #attributes, but when this node is serialized to XML an
-
# "xmlns" attribute will appear. See also #namespace and #namespace=
-
1
def default_namespace= url
-
add_namespace_definition(nil, url)
-
end
-
1
alias :add_namespace :add_namespace_definition
-
-
###
-
# Set the default namespace on this node (as would be defined with an
-
# "xmlns=" attribute in XML source), as a Namespace object +ns+. Note that
-
# a Namespace added this way will NOT be serialized as an xmlns attribute
-
# for this node. You probably want #default_namespace= instead, or perhaps
-
# #add_namespace_definition with a nil prefix argument.
-
1
def namespace= ns
-
return set_namespace(ns) unless ns
-
-
unless Nokogiri::XML::Namespace === ns
-
raise TypeError, "#{ns.class} can't be coerced into Nokogiri::XML::Namespace"
-
end
-
if ns.document != document
-
raise ArgumentError, 'namespace must be declared on the same document'
-
end
-
-
set_namespace ns
-
end
-
-
####
-
# Yields self and all children to +block+ recursively.
-
1
def traverse &block
-
children.each{|j| j.traverse(&block) }
-
block.call(self)
-
end
-
-
###
-
# Accept a visitor. This method calls "visit" on +visitor+ with self.
-
1
def accept visitor
-
visitor.visit(self)
-
end
-
-
###
-
# Test to see if this Node is equal to +other+
-
1
def == other
-
return false unless other
-
return false unless other.respond_to?(:pointer_id)
-
pointer_id == other.pointer_id
-
end
-
-
###
-
# Serialize Node using +options+. Save options can also be set using a
-
# block. See SaveOptions.
-
#
-
# These two statements are equivalent:
-
#
-
# node.serialize(:encoding => 'UTF-8', :save_with => FORMAT | AS_XML)
-
#
-
# or
-
#
-
# node.serialize(:encoding => 'UTF-8') do |config|
-
# config.format.as_xml
-
# end
-
#
-
1
def serialize *args, &block
-
options = args.first.is_a?(Hash) ? args.shift : {
-
:encoding => args[0],
-
:save_with => args[1]
-
}
-
-
encoding = options[:encoding] || document.encoding
-
options[:encoding] = encoding
-
-
outstring = ""
-
if encoding && outstring.respond_to?(:force_encoding)
-
outstring.force_encoding(Encoding.find(encoding))
-
end
-
io = StringIO.new(outstring)
-
write_to io, options, &block
-
io.string
-
end
-
-
###
-
# Serialize this Node to HTML
-
#
-
# doc.to_html
-
#
-
# See Node#write_to for a list of +options+. For formatted output,
-
# use Node#to_xhtml instead.
-
1
def to_html options = {}
-
# FIXME: this is a hack around broken libxml versions
-
return dump_html if Nokogiri.uses_libxml? && %w[2 6] === LIBXML_VERSION.split('.')[0..1]
-
-
options[:save_with] |= SaveOptions::DEFAULT_HTML if options[:save_with]
-
options[:save_with] = SaveOptions::DEFAULT_HTML unless options[:save_with]
-
serialize(options)
-
end
-
-
###
-
# Serialize this Node to XML using +options+
-
#
-
# doc.to_xml(:indent => 5, :encoding => 'UTF-8')
-
#
-
# See Node#write_to for a list of +options+
-
1
def to_xml options = {}
-
options[:save_with] ||= SaveOptions::DEFAULT_XML
-
serialize(options)
-
end
-
-
###
-
# Serialize this Node to XHTML using +options+
-
#
-
# doc.to_xhtml(:indent => 5, :encoding => 'UTF-8')
-
#
-
# See Node#write_to for a list of +options+
-
1
def to_xhtml options = {}
-
# FIXME: this is a hack around broken libxml versions
-
return dump_html if Nokogiri.uses_libxml? && %w[2 6] === LIBXML_VERSION.split('.')[0..1]
-
-
options[:save_with] |= SaveOptions::DEFAULT_XHTML if options[:save_with]
-
options[:save_with] = SaveOptions::DEFAULT_XHTML unless options[:save_with]
-
serialize(options)
-
end
-
-
###
-
# Write Node to +io+ with +options+. +options+ modify the output of
-
# this method. Valid options are:
-
#
-
# * +:encoding+ for changing the encoding
-
# * +:indent_text+ the indentation text, defaults to one space
-
# * +:indent+ the number of +:indent_text+ to use, defaults to 2
-
# * +:save_with+ a combination of SaveOptions constants.
-
#
-
# To save with UTF-8 indented twice:
-
#
-
# node.write_to(io, :encoding => 'UTF-8', :indent => 2)
-
#
-
# To save indented with two dashes:
-
#
-
# node.write_to(io, :indent_text => '-', :indent => 2
-
#
-
1
def write_to io, *options
-
options = options.first.is_a?(Hash) ? options.shift : {}
-
encoding = options[:encoding] || options[0]
-
if Nokogiri.jruby?
-
save_options = options[:save_with] || options[1]
-
indent_times = options[:indent] || 0
-
else
-
save_options = options[:save_with] || options[1] || SaveOptions::FORMAT
-
indent_times = options[:indent] || 2
-
end
-
indent_text = options[:indent_text] || ' '
-
-
config = SaveOptions.new(save_options.to_i)
-
yield config if block_given?
-
-
native_write_to(io, encoding, indent_text * indent_times, config.options)
-
end
-
-
###
-
# Write Node as HTML to +io+ with +options+
-
#
-
# See Node#write_to for a list of +options+
-
1
def write_html_to io, options = {}
-
# FIXME: this is a hack around broken libxml versions
-
return (io << dump_html) if Nokogiri.uses_libxml? && %w[2 6] === LIBXML_VERSION.split('.')[0..1]
-
-
options[:save_with] ||= SaveOptions::DEFAULT_HTML
-
write_to io, options
-
end
-
-
###
-
# Write Node as XHTML to +io+ with +options+
-
#
-
# See Node#write_to for a list of +options+
-
1
def write_xhtml_to io, options = {}
-
# FIXME: this is a hack around broken libxml versions
-
return (io << dump_html) if Nokogiri.uses_libxml? && %w[2 6] === LIBXML_VERSION.split('.')[0..1]
-
-
options[:save_with] ||= SaveOptions::DEFAULT_XHTML
-
write_to io, options
-
end
-
-
###
-
# Write Node as XML to +io+ with +options+
-
#
-
# doc.write_xml_to io, :encoding => 'UTF-8'
-
#
-
# See Node#write_to for a list of options
-
1
def write_xml_to io, options = {}
-
options[:save_with] ||= SaveOptions::DEFAULT_XML
-
write_to io, options
-
end
-
-
###
-
# Compare two Node objects with respect to their Document. Nodes from
-
# different documents cannot be compared.
-
1
def <=> other
-
return nil unless other.is_a?(Nokogiri::XML::Node)
-
return nil unless document == other.document
-
compare other
-
end
-
-
###
-
# Do xinclude substitution on the subtree below node. If given a block, a
-
# Nokogiri::XML::ParseOptions object initialized from +options+, will be
-
# passed to it, allowing more convenient modification of the parser options.
-
1
def do_xinclude options = XML::ParseOptions::DEFAULT_XML, &block
-
options = Nokogiri::XML::ParseOptions.new(options) if Fixnum === options
-
-
# give options to user
-
yield options if block_given?
-
-
# call c extension
-
process_xincludes(options.to_i)
-
end
-
-
1
def canonicalize(mode=XML::XML_C14N_1_0,inclusive_namespaces=nil,with_comments=false)
-
c14n_root = self
-
document.canonicalize(mode, inclusive_namespaces, with_comments) do |node, parent|
-
tn = node.is_a?(XML::Node) ? node : parent
-
tn == c14n_root || tn.ancestors.include?(c14n_root)
-
end
-
end
-
-
1
private
-
-
1
def extract_params params # :nodoc:
-
# Pop off our custom function handler if it exists
-
handler = params.find { |param|
-
![Hash, String, Symbol].include?(param.class)
-
}
-
-
params -= [handler] if handler
-
-
hashes = []
-
while Hash === params.last || params.last.nil?
-
hashes << params.pop
-
break if params.empty?
-
end
-
-
ns, binds = hashes.reverse
-
-
ns ||= document.root ? document.root.namespaces : {}
-
-
[params, handler, ns, binds]
-
end
-
-
1
def coerce data # :nodoc:
-
return data if data.is_a?(XML::NodeSet)
-
return data.children if data.is_a?(XML::DocumentFragment)
-
return fragment(data).children if data.is_a?(String)
-
-
if data.is_a?(Document) || data.is_a?(XML::Attr) || !data.is_a?(XML::Node)
-
raise ArgumentError, <<-EOERR
-
Requires a Node, NodeSet or String argument, and cannot accept a #{data.class}.
-
(You probably want to select a node from the Document with at() or search(), or create a new Node via Node.new().)
-
EOERR
-
end
-
-
data
-
end
-
-
1
def implied_xpath_context
-
"./"
-
end
-
-
1
def inspect_attributes
-
[:name, :namespace, :attribute_nodes, :children]
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class Node
-
###
-
# Save options for serializing nodes
-
1
class SaveOptions
-
# Format serialized xml
-
1
FORMAT = 1
-
# Do not include declarations
-
1
NO_DECLARATION = 2
-
# Do not include empty tags
-
1
NO_EMPTY_TAGS = 4
-
# Do not save XHTML
-
1
NO_XHTML = 8
-
# Save as XHTML
-
1
AS_XHTML = 16
-
# Save as XML
-
1
AS_XML = 32
-
# Save as HTML
-
1
AS_HTML = 64
-
-
1
if Nokogiri.jruby?
-
# Save builder created document
-
AS_BUILDER = 128
-
# the default for XML documents
-
DEFAULT_XML = AS_XML # https://github.com/sparklemotion/nokogiri/issues/#issue/415
-
# the default for HTML document
-
DEFAULT_HTML = NO_DECLARATION | NO_EMPTY_TAGS | AS_HTML
-
else
-
# the default for XML documents
-
1
DEFAULT_XML = FORMAT | AS_XML
-
# the default for HTML document
-
1
DEFAULT_HTML = FORMAT | NO_DECLARATION | NO_EMPTY_TAGS | AS_HTML
-
end
-
# the default for XHTML document
-
1
DEFAULT_XHTML = FORMAT | NO_DECLARATION | NO_EMPTY_TAGS | AS_XHTML
-
-
# Integer representation of the SaveOptions
-
1
attr_reader :options
-
-
# Create a new SaveOptions object with +options+
-
1
def initialize options = 0; @options = options; end
-
-
1
constants.each do |constant|
-
class_eval %{
-
def #{constant.downcase}
-
@options |= #{constant}
-
self
-
end
-
-
def #{constant.downcase}?
-
#{constant} & @options == #{constant}
-
end
-
10
}
-
end
-
-
1
alias :to_i :options
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
####
-
# A NodeSet contains a list of Nokogiri::XML::Node objects. Typically
-
# a NodeSet is return as a result of searching a Document via
-
# Nokogiri::XML::Node#css or Nokogiri::XML::Node#xpath
-
1
class NodeSet
-
1
include Enumerable
-
-
# The Document this NodeSet is associated with
-
1
attr_accessor :document
-
-
# Create a NodeSet with +document+ defaulting to +list+
-
1
def initialize document, list = []
-
@document = document
-
document.decorate(self)
-
list.each { |x| self << x }
-
yield self if block_given?
-
end
-
-
###
-
# Get the first element of the NodeSet.
-
1
def first n = nil
-
return self[0] unless n
-
list = []
-
0.upto(n - 1) do |i|
-
list << self[i]
-
end
-
list
-
end
-
-
###
-
# Get the last element of the NodeSet.
-
1
def last
-
self[length - 1]
-
end
-
-
###
-
# Is this NodeSet empty?
-
1
def empty?
-
length == 0
-
end
-
-
###
-
# Returns the index of the first node in self that is == to +node+. Returns nil if no match is found.
-
1
def index(node)
-
each_with_index { |member, j| return j if member == node }
-
nil
-
end
-
-
###
-
# Insert +datum+ before the first Node in this NodeSet
-
1
def before datum
-
first.before datum
-
end
-
-
###
-
# Insert +datum+ after the last Node in this NodeSet
-
1
def after datum
-
last.after datum
-
end
-
-
1
alias :<< :push
-
1
alias :remove :unlink
-
-
###
-
# Search this document for +paths+
-
#
-
# For more information see Nokogiri::XML::Node#css and
-
# Nokogiri::XML::Node#xpath
-
1
def search *paths
-
handler = ![
-
Hash, String, Symbol
-
].include?(paths.last.class) ? paths.pop : nil
-
-
ns = paths.last.is_a?(Hash) ? paths.pop : nil
-
-
sub_set = NodeSet.new(document)
-
-
paths.each do |path|
-
sub_set += send(
-
path =~ /^(\.\/|\/|\.\.|\.$)/ ? :xpath : :css,
-
*(paths + [ns, handler]).compact
-
)
-
end
-
-
document.decorate(sub_set)
-
sub_set
-
end
-
1
alias :/ :search
-
-
###
-
# Search this NodeSet for css +paths+
-
#
-
# For more information see Nokogiri::XML::Node#css
-
1
def css *paths
-
handler = ![
-
Hash, String, Symbol
-
].include?(paths.last.class) ? paths.pop : nil
-
-
ns = paths.last.is_a?(Hash) ? paths.pop : nil
-
-
sub_set = NodeSet.new(document)
-
-
each do |node|
-
doc = node.document
-
search_ns = ns || (doc.root ? doc.root.namespaces : {})
-
-
xpaths = paths.map { |rule|
-
[
-
CSS.xpath_for(rule.to_s, :prefix => ".//", :ns => search_ns),
-
CSS.xpath_for(rule.to_s, :prefix => "self::", :ns => search_ns)
-
].join(' | ')
-
}
-
-
sub_set += node.xpath(*(xpaths + [search_ns, handler].compact))
-
end
-
document.decorate(sub_set)
-
sub_set
-
end
-
-
###
-
# Search this NodeSet for XPath +paths+
-
#
-
# For more information see Nokogiri::XML::Node#xpath
-
1
def xpath *paths
-
handler = ![
-
Hash, String, Symbol
-
].include?(paths.last.class) ? paths.pop : nil
-
-
ns = paths.last.is_a?(Hash) ? paths.pop : nil
-
-
sub_set = NodeSet.new(document)
-
each do |node|
-
sub_set += node.xpath(*(paths + [ns, handler].compact))
-
end
-
document.decorate(sub_set)
-
sub_set
-
end
-
-
###
-
# Search this NodeSet's nodes' immediate children using CSS selector +selector+
-
1
def > selector
-
ns = document.root.namespaces
-
xpath CSS.xpath_for(selector, :prefix => "./", :ns => ns).first
-
end
-
-
###
-
# If path is a string, search this document for +path+ returning the
-
# first Node. Otherwise, index in to the array with +path+.
-
1
def at path, ns = document.root ? document.root.namespaces : {}
-
return self[path] if path.is_a?(Numeric)
-
search(path, ns).first
-
end
-
1
alias :% :at
-
-
##
-
# Search this NodeSet for the first occurrence of XPath +paths+.
-
# Equivalent to <tt>xpath(paths).first</tt>
-
# See NodeSet#xpath for more information.
-
#
-
1
def at_xpath *paths
-
xpath(*paths).first
-
end
-
-
##
-
# Search this NodeSet for the first occurrence of CSS +rules+.
-
# Equivalent to <tt>css(rules).first</tt>
-
# See NodeSet#css for more information.
-
#
-
1
def at_css *rules
-
css(*rules).first
-
end
-
-
###
-
# Filter this list for nodes that match +expr+
-
1
def filter expr
-
find_all { |node| node.matches?(expr) }
-
end
-
-
###
-
# Append the class attribute +name+ to all Node objects in the NodeSet.
-
1
def add_class name
-
each do |el|
-
classes = el['class'].to_s.split(/\s+/)
-
el['class'] = classes.push(name).uniq.join " "
-
end
-
self
-
end
-
-
###
-
# Remove the class attribute +name+ from all Node objects in the NodeSet.
-
# If +name+ is nil, remove the class attribute from all Nodes in the
-
# NodeSet.
-
1
def remove_class name = nil
-
each do |el|
-
if name
-
classes = el['class'].to_s.split(/\s+/)
-
if classes.empty?
-
el.delete 'class'
-
else
-
el['class'] = (classes - [name]).uniq.join " "
-
end
-
else
-
el.delete "class"
-
end
-
end
-
self
-
end
-
-
###
-
# Set the attribute +key+ to +value+ or the return value of +blk+
-
# on all Node objects in the NodeSet.
-
1
def attr key, value = nil, &blk
-
unless Hash === key || key && (value || blk)
-
return first.attribute(key)
-
end
-
-
hash = key.is_a?(Hash) ? key : { key => value }
-
-
hash.each { |k,v| each { |el| el[k] = v || blk[el] } }
-
-
self
-
end
-
1
alias :set :attr
-
1
alias :attribute :attr
-
-
###
-
# Remove the attributed named +name+ from all Node objects in the NodeSet
-
1
def remove_attr name
-
each { |el| el.delete name }
-
self
-
end
-
-
###
-
# Iterate over each node, yielding to +block+
-
1
def each(&block)
-
33
0.upto(length - 1) do |x|
-
67
yield self[x]
-
end
-
end
-
-
###
-
# Get the inner text of all contained Node objects
-
1
def inner_text
-
collect{|j| j.inner_text}.join('')
-
end
-
1
alias :text :inner_text
-
-
###
-
# Get the inner html of all contained Node objects
-
1
def inner_html *args
-
collect{|j| j.inner_html(*args) }.join('')
-
end
-
-
###
-
# Wrap this NodeSet with +html+ or the results of the builder in +blk+
-
1
def wrap(html, &blk)
-
each do |j|
-
new_parent = document.parse(html).first
-
j.add_next_sibling(new_parent)
-
new_parent.add_child(j)
-
end
-
self
-
end
-
-
###
-
# Convert this NodeSet to a string.
-
1
def to_s
-
map { |x| x.to_s }.join
-
end
-
-
###
-
# Convert this NodeSet to HTML
-
1
def to_html *args
-
if Nokogiri.jruby?
-
options = args.first.is_a?(Hash) ? args.shift : {}
-
if !options[:save_with]
-
options[:save_with] = Node::SaveOptions::NO_DECLARATION | Node::SaveOptions::NO_EMPTY_TAGS | Node::SaveOptions::AS_HTML
-
end
-
args.insert(0, options)
-
end
-
map { |x| x.to_html(*args) }.join
-
end
-
-
###
-
# Convert this NodeSet to XHTML
-
1
def to_xhtml *args
-
map { |x| x.to_xhtml(*args) }.join
-
end
-
-
###
-
# Convert this NodeSet to XML
-
1
def to_xml *args
-
map { |x| x.to_xml(*args) }.join
-
end
-
-
1
alias :size :length
-
1
alias :to_ary :to_a
-
-
###
-
# Removes the last element from set and returns it, or +nil+ if
-
# the set is empty
-
1
def pop
-
return nil if length == 0
-
delete last
-
end
-
-
###
-
# Returns the first element of the NodeSet and removes it. Returns
-
# +nil+ if the set is empty.
-
1
def shift
-
return nil if length == 0
-
delete first
-
end
-
-
###
-
# Equality -- Two NodeSets are equal if the contain the same number
-
# of elements and if each element is equal to the corresponding
-
# element in the other NodeSet
-
1
def == other
-
return false unless other.is_a?(Nokogiri::XML::NodeSet)
-
return false unless length == other.length
-
each_with_index do |node, i|
-
return false unless node == other[i]
-
end
-
true
-
end
-
-
###
-
# Returns a new NodeSet containing all the children of all the nodes in
-
# the NodeSet
-
1
def children
-
inject(NodeSet.new(document)) { |set, node| set += node.children }
-
end
-
-
###
-
# Returns a new NodeSet containing all the nodes in the NodeSet
-
# in reverse order
-
1
def reverse
-
node_set = NodeSet.new(document)
-
(length - 1).downto(0) do |x|
-
node_set.push self[x]
-
end
-
node_set
-
end
-
-
###
-
# Return a nicely formated string representation
-
1
def inspect
-
"[#{map { |c| c.inspect }.join ', '}]"
-
end
-
-
1
alias :+ :|
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class Notation < Struct.new(:name, :public_id, :system_id)
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
###
-
# Parse options for passing to Nokogiri.XML or Nokogiri.HTML
-
1
class ParseOptions
-
# Strict parsing
-
1
STRICT = 0
-
# Recover from errors
-
1
RECOVER = 1 << 0
-
# Substitute entities
-
1
NOENT = 1 << 1
-
# Load external subsets
-
1
DTDLOAD = 1 << 2
-
# Default DTD attributes
-
1
DTDATTR = 1 << 3
-
# validate with the DTD
-
1
DTDVALID = 1 << 4
-
# suppress error reports
-
1
NOERROR = 1 << 5
-
# suppress warning reports
-
1
NOWARNING = 1 << 6
-
# pedantic error reporting
-
1
PEDANTIC = 1 << 7
-
# remove blank nodes
-
1
NOBLANKS = 1 << 8
-
# use the SAX1 interface internally
-
1
SAX1 = 1 << 9
-
# Implement XInclude substitution
-
1
XINCLUDE = 1 << 10
-
# Forbid network access. Recommended for dealing with untrusted documents.
-
1
NONET = 1 << 11
-
# Do not reuse the context dictionary
-
1
NODICT = 1 << 12
-
# remove redundant namespaces declarations
-
1
NSCLEAN = 1 << 13
-
# merge CDATA as text nodes
-
1
NOCDATA = 1 << 14
-
# do not generate XINCLUDE START/END nodes
-
1
NOXINCNODE = 1 << 15
-
# compact small text nodes; no modification of the tree allowed afterwards (will possibly crash if you try to modify the tree)
-
1
COMPACT = 1 << 16
-
# parse using XML-1.0 before update 5
-
1
OLD10 = 1 << 17
-
# do not fixup XINCLUDE xml:base uris
-
1
NOBASEFIX = 1 << 18
-
# relax any hardcoded limit from the parser
-
1
HUGE = 1 << 19
-
-
# the default options used for parsing XML documents
-
1
DEFAULT_XML = RECOVER | NONET
-
# the default options used for parsing HTML documents
-
1
DEFAULT_HTML = RECOVER | NOERROR | NOWARNING | NONET
-
-
1
attr_accessor :options
-
1
def initialize options = STRICT
-
17
@options = options
-
end
-
-
1
constants.each do |constant|
-
23
next if constant.to_sym == :STRICT
-
class_eval %{
-
def #{constant.downcase}
-
@options |= #{constant}
-
self
-
end
-
-
def no#{constant.downcase}
-
@options &= ~#{constant}
-
self
-
end
-
-
def #{constant.downcase}?
-
#{constant} & @options == #{constant}
-
end
-
22
}
-
end
-
-
1
def strict
-
@options &= ~RECOVER
-
self
-
end
-
-
1
def strict?
-
@options & RECOVER == STRICT
-
end
-
-
1
alias :to_i :options
-
-
1
def inspect
-
options = []
-
self.class.constants.each do |k|
-
options << k.downcase if send(:"#{k.downcase}?")
-
end
-
super.sub(/>$/, " " + options.join(', ') + ">")
-
end
-
end
-
end
-
end
-
1
require 'nokogiri/xml/pp/node'
-
1
require 'nokogiri/xml/pp/character_data'
-
1
module Nokogiri
-
1
module XML
-
1
module PP
-
1
module CharacterData
-
1
def pretty_print pp # :nodoc:
-
nice_name = self.class.name.split('::').last
-
pp.group(2, "#(#{nice_name} ", ')') do
-
pp.pp text
-
end
-
end
-
-
1
def inspect # :nodoc:
-
"#<#{self.class.name}:#{sprintf("0x%x",object_id)} #{text.inspect}>"
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
module PP
-
1
module Node
-
1
def inspect # :nodoc:
-
attributes = inspect_attributes.reject { |x|
-
begin
-
attribute = send x
-
!attribute || (attribute.respond_to?(:empty?) && attribute.empty?)
-
rescue NoMethodError
-
true
-
end
-
}.map { |attribute|
-
"#{attribute.to_s.sub(/_\w+/, 's')}=#{send(attribute).inspect}"
-
}.join ' '
-
"#<#{self.class.name}:#{sprintf("0x%x", object_id)} #{attributes}>"
-
end
-
-
1
def pretty_print pp # :nodoc:
-
nice_name = self.class.name.split('::').last
-
pp.group(2, "#(#{nice_name}:#{sprintf("0x%x", object_id)} {", '})') do
-
-
pp.breakable
-
attrs = inspect_attributes.map { |t|
-
[t, send(t)] if respond_to?(t)
-
}.compact.find_all { |x|
-
if x.last
-
if [:attribute_nodes, :children].include? x.first
-
!x.last.empty?
-
else
-
true
-
end
-
end
-
}
-
-
pp.seplist(attrs) do |v|
-
if [:attribute_nodes, :children].include? v.first
-
pp.group(2, "#{v.first.to_s.sub(/_\w+$/, 's')} = [", "]") do
-
pp.breakable
-
pp.seplist(v.last) do |item|
-
pp.pp item
-
end
-
end
-
else
-
pp.text "#{v.first} = "
-
pp.pp v.last
-
end
-
end
-
pp.breakable
-
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class ProcessingInstruction < Node
-
1
def initialize document, name, content
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class << self
-
###
-
# Create a new Nokogiri::XML::RelaxNG document from +string_or_io+.
-
# See Nokogiri::XML::RelaxNG for an example.
-
1
def RelaxNG string_or_io
-
RelaxNG.new(string_or_io)
-
end
-
end
-
-
###
-
# Nokogiri::XML::RelaxNG is used for validating XML against a
-
# RelaxNG schema.
-
#
-
# == Synopsis
-
#
-
# Validate an XML document against a RelaxNG schema. Loop over the errors
-
# that are returned and print them out:
-
#
-
# schema = Nokogiri::XML::RelaxNG(File.open(ADDRESS_SCHEMA_FILE))
-
# doc = Nokogiri::XML(File.open(ADDRESS_XML_FILE))
-
#
-
# schema.validate(doc).each do |error|
-
# puts error.message
-
# end
-
#
-
# The list of errors are Nokogiri::XML::SyntaxError objects.
-
1
class RelaxNG < Nokogiri::XML::Schema
-
end
-
end
-
end
-
1
require 'nokogiri/xml/sax/document'
-
1
require 'nokogiri/xml/sax/parser_context'
-
1
require 'nokogiri/xml/sax/parser'
-
1
require 'nokogiri/xml/sax/push_parser'
-
1
module Nokogiri
-
1
module XML
-
###
-
# SAX Parsers are event driven parsers. Nokogiri provides two different
-
# event based parsers when dealing with XML. If you want to do SAX style
-
# parsing using HTML, check out Nokogiri::HTML::SAX.
-
#
-
# The basic way a SAX style parser works is by creating a parser,
-
# telling the parser about the events we're interested in, then giving
-
# the parser some XML to process. The parser will notify you when
-
# it encounters events your said you would like to know about.
-
#
-
# To register for events, you simply subclass Nokogiri::XML::SAX::Document,
-
# and implement the methods for which you would like notification.
-
#
-
# For example, if I want to be notified when a document ends, and when an
-
# element starts, I would write a class like this:
-
#
-
# class MyDocument < Nokogiri::XML::SAX::Document
-
# def end_document
-
# puts "the document has ended"
-
# end
-
#
-
# def start_element name, attributes = []
-
# puts "#{name} started"
-
# end
-
# end
-
#
-
# Then I would instantiate a SAX parser with this document, and feed the
-
# parser some XML
-
#
-
# # Create a new parser
-
# parser = Nokogiri::XML::SAX::Parser.new(MyDocument.new)
-
#
-
# # Feed the parser some XML
-
# parser.parse(File.open(ARGV[0]))
-
#
-
# Now my document handler will be called when each node starts, and when
-
# then document ends. To see what kinds of events are available, take
-
# a look at Nokogiri::XML::SAX::Document.
-
#
-
# Two SAX parsers for XML are available, a parser that reads from a string
-
# or IO object as it feels necessary, and a parser that lets you spoon
-
# feed it XML. If you want to let Nokogiri deal with reading your XML,
-
# use the Nokogiri::XML::SAX::Parser. If you want to have fine grain
-
# control over the XML input, use the Nokogiri::XML::SAX::PushParser.
-
1
module SAX
-
###
-
# This class is used for registering types of events you are interested
-
# in handling. All of the methods on this class are available as
-
# possible events while parsing an XML document. To register for any
-
# particular event, just subclass this class and implement the methods
-
# you are interested in knowing about.
-
#
-
# To only be notified about start and end element events, write a class
-
# like this:
-
#
-
# class MyDocument < Nokogiri::XML::SAX::Document
-
# def start_element name, attrs = []
-
# puts "#{name} started!"
-
# end
-
#
-
# def end_element name
-
# puts "#{name} ended"
-
# end
-
# end
-
#
-
# You can use this event handler for any SAX style parser included with
-
# Nokogiri. See Nokogiri::XML::SAX, and Nokogiri::HTML::SAX.
-
1
class Document
-
###
-
# Called when an XML declaration is parsed
-
1
def xmldecl version, encoding, standalone
-
end
-
-
###
-
# Called when document starts parsing
-
1
def start_document
-
end
-
-
###
-
# Called when document ends parsing
-
1
def end_document
-
end
-
-
###
-
# Called at the beginning of an element
-
# * +name+ is the name of the tag
-
# * +attrs+ are an assoc list of namespaces and attributes, e.g.:
-
# [ ["xmlns:foo", "http://sample.net"], ["size", "large"] ]
-
1
def start_element name, attrs = []
-
end
-
-
###
-
# Called at the end of an element
-
# +name+ is the tag name
-
1
def end_element name
-
end
-
-
###
-
# Called at the beginning of an element
-
# +name+ is the element name
-
# +attrs+ is a list of attributes
-
# +prefix+ is the namespace prefix for the element
-
# +uri+ is the associated namespace URI
-
# +ns+ is a hash of namespace prefix:urls associated with the element
-
1
def start_element_namespace name, attrs = [], prefix = nil, uri = nil, ns = []
-
###
-
# Deal with SAX v1 interface
-
33
name = [prefix, name].compact.join(':')
-
33
attributes = ns.map { |ns_prefix,ns_uri|
-
[['xmlns', ns_prefix].compact.join(':'), ns_uri]
-
} + attrs.map { |attr|
-
14
[[attr.prefix, attr.localname].compact.join(':'), attr.value]
-
}
-
33
start_element name, attributes
-
end
-
-
###
-
# Called at the end of an element
-
# +name+ is the element's name
-
# +prefix+ is the namespace prefix associated with the element
-
# +uri+ is the associated namespace URI
-
1
def end_element_namespace name, prefix = nil, uri = nil
-
###
-
# Deal with SAX v1 interface
-
33
end_element [prefix, name].compact.join(':')
-
end
-
-
###
-
# Characters read between a tag. This method might be called multiple
-
# times given one contiguous string of characters.
-
#
-
# +string+ contains the character data
-
1
def characters string
-
end
-
-
###
-
# Called when comments are encountered
-
# +string+ contains the comment data
-
1
def comment string
-
end
-
-
###
-
# Called on document warnings
-
# +string+ contains the warning
-
1
def warning string
-
end
-
-
###
-
# Called on document errors
-
# +string+ contains the error
-
1
def error string
-
end
-
-
###
-
# Called when cdata blocks are found
-
# +string+ contains the cdata content
-
1
def cdata_block string
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
module SAX
-
###
-
# This parser is a SAX style parser that reads it's input as it
-
# deems necessary. The parser takes a Nokogiri::XML::SAX::Document,
-
# an optional encoding, then given an XML input, sends messages to
-
# the Nokogiri::XML::SAX::Document.
-
#
-
# Here is an example of using this parser:
-
#
-
# # Create a subclass of Nokogiri::XML::SAX::Document and implement
-
# # the events we care about:
-
# class MyDoc < Nokogiri::XML::SAX::Document
-
# def start_element name, attrs = []
-
# puts "starting: #{name}"
-
# end
-
#
-
# def end_element name
-
# puts "ending: #{name}"
-
# end
-
# end
-
#
-
# # Create our parser
-
# parser = Nokogiri::XML::SAX::Parser.new(MyDoc.new)
-
#
-
# # Send some XML to the parser
-
# parser.parse(File.open(ARGV[0]))
-
#
-
# For more information about SAX parsers, see Nokogiri::XML::SAX. Also
-
# see Nokogiri::XML::SAX::Document for the available events.
-
1
class Parser
-
1
class Attribute < Struct.new(:localname, :prefix, :uri, :value)
-
end
-
-
# Encodinds this parser supports
-
1
ENCODINGS = {
-
'NONE' => 0, # No char encoding detected
-
'UTF-8' => 1, # UTF-8
-
'UTF16LE' => 2, # UTF-16 little endian
-
'UTF16BE' => 3, # UTF-16 big endian
-
'UCS4LE' => 4, # UCS-4 little endian
-
'UCS4BE' => 5, # UCS-4 big endian
-
'EBCDIC' => 6, # EBCDIC uh!
-
'UCS4-2143' => 7, # UCS-4 unusual ordering
-
'UCS4-3412' => 8, # UCS-4 unusual ordering
-
'UCS2' => 9, # UCS-2
-
'ISO-8859-1' => 10, # ISO-8859-1 ISO Latin 1
-
'ISO-8859-2' => 11, # ISO-8859-2 ISO Latin 2
-
'ISO-8859-3' => 12, # ISO-8859-3
-
'ISO-8859-4' => 13, # ISO-8859-4
-
'ISO-8859-5' => 14, # ISO-8859-5
-
'ISO-8859-6' => 15, # ISO-8859-6
-
'ISO-8859-7' => 16, # ISO-8859-7
-
'ISO-8859-8' => 17, # ISO-8859-8
-
'ISO-8859-9' => 18, # ISO-8859-9
-
'ISO-2022-JP' => 19, # ISO-2022-JP
-
'SHIFT-JIS' => 20, # Shift_JIS
-
'EUC-JP' => 21, # EUC-JP
-
'ASCII' => 22, # pure ASCII
-
}
-
-
# The Nokogiri::XML::SAX::Document where events will be sent.
-
1
attr_accessor :document
-
-
# The encoding beings used for this document.
-
1
attr_accessor :encoding
-
-
# Create a new Parser with +doc+ and +encoding+
-
1
def initialize doc = Nokogiri::XML::SAX::Document.new, encoding = 'UTF-8'
-
17
@encoding = encoding
-
17
@document = doc
-
17
@warned = false
-
end
-
-
###
-
# Parse given +thing+ which may be a string containing xml, or an
-
# IO object.
-
1
def parse thing, &block
-
17
if thing.respond_to?(:read) && thing.respond_to?(:close)
-
17
parse_io(thing, &block)
-
else
-
parse_memory(thing, &block)
-
end
-
end
-
-
###
-
# Parse given +io+
-
1
def parse_io io, encoding = 'ASCII'
-
17
@encoding = encoding
-
17
ctx = ParserContext.io(io, ENCODINGS[encoding])
-
17
yield ctx if block_given?
-
17
ctx.parse_with self
-
end
-
-
###
-
# Parse a file with +filename+
-
1
def parse_file filename
-
raise ArgumentError unless filename
-
raise Errno::ENOENT unless File.exists?(filename)
-
raise Errno::EISDIR if File.directory?(filename)
-
ctx = ParserContext.file filename
-
yield ctx if block_given?
-
ctx.parse_with self
-
end
-
-
1
def parse_memory data
-
ctx = ParserContext.memory data
-
yield ctx if block_given?
-
ctx.parse_with self
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
module SAX
-
###
-
# Context for XML SAX parsers. This class is usually not instantiated
-
# by the user. Instead, you should be looking at
-
# Nokogiri::XML::SAX::Parser
-
1
class ParserContext
-
1
def self.new thing, encoding = 'UTF-8'
-
[:read, :close].all? { |x| thing.respond_to?(x) } ?
-
io(thing, Parser::ENCODINGS[encoding]) : memory(thing)
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
module SAX
-
###
-
# PushParser can parse a document that is fed to it manually. It
-
# must be given a SAX::Document object which will be called with
-
# SAX events as the document is being parsed.
-
#
-
# Calling PushParser#<< writes XML to the parser, calling any SAX
-
# callbacks it can.
-
#
-
# PushParser#finish tells the parser that the document is finished
-
# and calls the end_document SAX method.
-
#
-
# Example:
-
#
-
# parser = PushParser.new(Class.new(XML::SAX::Document) {
-
# def start_document
-
# puts "start document called"
-
# end
-
# }.new)
-
# parser << "<div>hello<"
-
# parser << "/div>"
-
# parser.finish
-
1
class PushParser
-
-
# The Nokogiri::XML::SAX::Document on which the PushParser will be
-
# operating
-
1
attr_accessor :document
-
-
###
-
# Create a new PushParser with +doc+ as the SAX Document, providing
-
# an optional +file_name+ and +encoding+
-
1
def initialize(doc = XML::SAX::Document.new, file_name = nil, encoding = 'UTF-8')
-
@document = doc
-
@encoding = encoding
-
@sax_parser = XML::SAX::Parser.new(doc)
-
-
## Create our push parser context
-
initialize_native(@sax_parser, file_name)
-
end
-
-
###
-
# Write a +chunk+ of XML to the PushParser. Any callback methods
-
# that can be called will be called immediately.
-
1
def write chunk, last_chunk = false
-
native_write(chunk, last_chunk)
-
end
-
1
alias :<< :write
-
-
###
-
# Finish the parsing. This method is only necessary for
-
# Nokogiri::XML::SAX::Document#end_document to be called.
-
1
def finish
-
write '', true
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class << self
-
###
-
# Create a new Nokogiri::XML::Schema object using a +string_or_io+
-
# object.
-
1
def Schema string_or_io
-
Schema.new(string_or_io)
-
end
-
end
-
-
###
-
# Nokogiri::XML::Schema is used for validating XML against a schema
-
# (usually from an xsd file).
-
#
-
# == Synopsis
-
#
-
# Validate an XML document against a Schema. Loop over the errors that
-
# are returned and print them out:
-
#
-
# xsd = Nokogiri::XML::Schema(File.read(PO_SCHEMA_FILE))
-
# doc = Nokogiri::XML(File.read(PO_XML_FILE))
-
#
-
# xsd.validate(doc).each do |error|
-
# puts error.message
-
# end
-
#
-
# The list of errors are Nokogiri::XML::SyntaxError objects.
-
1
class Schema
-
# Errors while parsing the schema file
-
1
attr_accessor :errors
-
-
###
-
# Create a new Nokogiri::XML::Schema object using a +string_or_io+
-
# object.
-
1
def self.new string_or_io
-
from_document Nokogiri::XML(string_or_io)
-
end
-
-
###
-
# Validate +thing+ against this schema. +thing+ can be a
-
# Nokogiri::XML::Document object, or a filename. An Array of
-
# Nokogiri::XML::SyntaxError objects found while validating the
-
# +thing+ is returned.
-
1
def validate thing
-
if thing.is_a?(Nokogiri::XML::Document)
-
validate_document(thing)
-
elsif File.file?(thing)
-
validate_file(thing)
-
else
-
raise ArgumentError, "Must provide Nokogiri::Xml::Document or the name of an existing file"
-
end
-
end
-
-
###
-
# Returns true if +thing+ is a valid Nokogiri::XML::Document or
-
# file.
-
1
def valid? thing
-
validate(thing).length == 0
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
###
-
# This class provides information about XML SyntaxErrors. These
-
# exceptions are typically stored on Nokogiri::XML::Document#errors.
-
1
class SyntaxError < ::Nokogiri::SyntaxError
-
1
attr_reader :domain
-
1
attr_reader :code
-
1
attr_reader :level
-
1
attr_reader :file
-
1
attr_reader :line
-
1
attr_reader :str1
-
1
attr_reader :str2
-
1
attr_reader :str3
-
1
attr_reader :int1
-
1
attr_reader :column
-
-
###
-
# return true if this is a non error
-
1
def none?
-
level == 0
-
end
-
-
###
-
# return true if this is a warning
-
1
def warning?
-
level == 1
-
end
-
-
###
-
# return true if this is an error
-
1
def error?
-
level == 2
-
end
-
-
###
-
# return true if this error is fatal
-
1
def fatal?
-
level == 3
-
end
-
-
1
def to_s
-
1
super.chomp
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class Text < Nokogiri::XML::CharacterData
-
1
def content=(string)
-
self.native_content = string.to_s
-
end
-
end
-
end
-
end
-
1
require 'nokogiri/xml/xpath/syntax_error'
-
-
1
module Nokogiri
-
1
module XML
-
1
class XPath
-
# The Nokogiri::XML::Document tied to this XPath instance
-
1
attr_accessor :document
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class XPath
-
1
class SyntaxError < XML::SyntaxError
-
1
def to_s
-
[super.chomp, str1].compact.join(': ')
-
end
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XML
-
1
class XPathContext
-
-
###
-
# Register namespaces in +namespaces+
-
1
def register_namespaces(namespaces)
-
namespaces.each do |k, v|
-
k = k.gsub(/.*:/,'') # strip off 'xmlns:' or 'xml:'
-
register_ns(k, v)
-
end
-
end
-
-
end
-
end
-
end
-
1
require 'nokogiri/xslt/stylesheet'
-
-
1
module Nokogiri
-
1
class << self
-
###
-
# Create a Nokogiri::XSLT::Stylesheet with +stylesheet+.
-
#
-
# Example:
-
#
-
# xslt = Nokogiri::XSLT(File.read(ARGV[0]))
-
#
-
1
def XSLT stylesheet, modules = {}
-
XSLT.parse(stylesheet, modules)
-
end
-
end
-
-
###
-
# See Nokogiri::XSLT::Stylesheet for creating and manipulating
-
# Stylesheet object.
-
1
module XSLT
-
1
class << self
-
###
-
# Parse the stylesheet in +string+, register any +modules+
-
1
def parse string, modules = {}
-
modules.each do |url, klass|
-
XSLT.register url, klass
-
end
-
-
if Nokogiri.jruby?
-
Stylesheet.parse_stylesheet_doc(XML.parse(string), string)
-
else
-
Stylesheet.parse_stylesheet_doc(XML.parse(string))
-
end
-
end
-
-
###
-
# Quote parameters in +params+ for stylesheet safety
-
1
def quote_params params
-
parray = (params.instance_of?(Hash) ? params.to_a.flatten : params).dup
-
parray.each_with_index do |v,i|
-
if i % 2 > 0
-
parray[i]=
-
if v =~ /'/
-
"concat('#{ v.gsub(/'/, %q{', "'", '}) }')"
-
else
-
"'#{v}'";
-
end
-
else
-
parray[i] = v.to_s
-
end
-
end
-
parray.flatten
-
end
-
end
-
end
-
end
-
1
module Nokogiri
-
1
module XSLT
-
###
-
# A Stylesheet represents an XSLT Stylesheet object. Stylesheet creation
-
# is done through Nokogiri.XSLT. Here is an example of transforming
-
# an XML::Document with a Stylesheet:
-
#
-
# doc = Nokogiri::XML(File.read('some_file.xml'))
-
# xslt = Nokogiri::XSLT(File.read('some_transformer.xslt'))
-
#
-
# puts xslt.transform(doc)
-
#
-
# See Nokogiri::XSLT::Stylesheet#transform for more transformation
-
# information.
-
1
class Stylesheet
-
###
-
# Apply an XSLT stylesheet to an XML::Document.
-
# +params+ is an array of strings used as XSLT parameters.
-
# returns serialized document
-
1
def apply_to document, params = []
-
serialize(transform(document, params))
-
end
-
end
-
end
-
end
-
# Define a package task library to aid in the definition of
-
# redistributable package files.
-
-
1
require 'rake'
-
1
require 'rake/tasklib'
-
-
1
module Rake
-
-
# Create a packaging task that will package the project into
-
# distributable files (e.g zip archive or tar files).
-
#
-
# The PackageTask will create the following targets:
-
#
-
# [<b>:package</b>]
-
# Create all the requested package files.
-
#
-
# [<b>:clobber_package</b>]
-
# Delete all the package files. This target is automatically
-
# added to the main clobber target.
-
#
-
# [<b>:repackage</b>]
-
# Rebuild the package files from scratch, even if they are not out
-
# of date.
-
#
-
# [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.tgz"</b>]
-
# Create a gzipped tar package (if <em>need_tar</em> is true).
-
#
-
# [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.tar.gz"</b>]
-
# Create a gzipped tar package (if <em>need_tar_gz</em> is true).
-
#
-
# [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.tar.bz2"</b>]
-
# Create a bzip2'd tar package (if <em>need_tar_bz2</em> is true).
-
#
-
# [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.zip"</b>]
-
# Create a zip package archive (if <em>need_zip</em> is true).
-
#
-
# Example:
-
#
-
# Rake::PackageTask.new("rake", "1.2.3") do |p|
-
# p.need_tar = true
-
# p.package_files.include("lib/**/*.rb")
-
# end
-
#
-
1
class PackageTask < TaskLib
-
# Name of the package (from the GEM Spec).
-
1
attr_accessor :name
-
-
# Version of the package (e.g. '1.3.2').
-
1
attr_accessor :version
-
-
# Directory used to store the package files (default is 'pkg').
-
1
attr_accessor :package_dir
-
-
# True if a gzipped tar file (tgz) should be produced (default is false).
-
1
attr_accessor :need_tar
-
-
# True if a gzipped tar file (tar.gz) should be produced (default is false).
-
1
attr_accessor :need_tar_gz
-
-
# True if a bzip2'd tar file (tar.bz2) should be produced (default is false).
-
1
attr_accessor :need_tar_bz2
-
-
# True if a zip file should be produced (default is false)
-
1
attr_accessor :need_zip
-
-
# List of files to be included in the package.
-
1
attr_accessor :package_files
-
-
# Tar command for gzipped or bzip2ed archives. The default is 'tar'.
-
1
attr_accessor :tar_command
-
-
# Zip command for zipped archives. The default is 'zip'.
-
1
attr_accessor :zip_command
-
-
# Create a Package Task with the given name and version. Use +:noversion+
-
# as the version to build a package without a version or to provide a
-
# fully-versioned package name.
-
-
1
def initialize(name=nil, version=nil)
-
init(name, version)
-
yield self if block_given?
-
define unless name.nil?
-
end
-
-
# Initialization that bypasses the "yield self" and "define" step.
-
1
def init(name, version)
-
1
@name = name
-
1
@version = version
-
1
@package_files = Rake::FileList.new
-
1
@package_dir = 'pkg'
-
1
@need_tar = false
-
1
@need_tar_gz = false
-
1
@need_tar_bz2 = false
-
1
@need_zip = false
-
1
@tar_command = 'tar'
-
1
@zip_command = 'zip'
-
end
-
-
# Create the tasks defined by this task library.
-
1
def define
-
1
fail "Version required (or :noversion)" if @version.nil?
-
1
@version = nil if :noversion == @version
-
-
1
desc "Build all the packages"
-
1
task :package
-
-
1
desc "Force a rebuild of the package files"
-
1
task :repackage => [:clobber_package, :package]
-
-
1
desc "Remove package products"
-
1
task :clobber_package do
-
rm_r package_dir rescue nil
-
end
-
-
1
task :clobber => [:clobber_package]
-
-
[
-
1
[need_tar, tgz_file, "z"],
-
[need_tar_gz, tar_gz_file, "z"],
-
[need_tar_bz2, tar_bz2_file, "j"]
-
].each do |(need, file, flag)|
-
3
if need
-
task :package => ["#{package_dir}/#{file}"]
-
file "#{package_dir}/#{file}" => [package_dir_path] + package_files do
-
chdir(package_dir) do
-
sh %{#{@tar_command} #{flag}cvf #{file} #{package_name}}
-
end
-
end
-
end
-
end
-
-
1
if need_zip
-
task :package => ["#{package_dir}/#{zip_file}"]
-
file "#{package_dir}/#{zip_file}" => [package_dir_path] + package_files do
-
chdir(package_dir) do
-
sh %{#{@zip_command} -r #{zip_file} #{package_name}}
-
end
-
end
-
end
-
-
1
directory package_dir
-
-
1
file package_dir_path => @package_files do
-
mkdir_p package_dir rescue nil
-
@package_files.each do |fn|
-
f = File.join(package_dir_path, fn)
-
fdir = File.dirname(f)
-
mkdir_p(fdir) if !File.exist?(fdir)
-
if File.directory?(fn)
-
mkdir_p(f)
-
else
-
rm_f f
-
safe_ln(fn, f)
-
end
-
end
-
end
-
1
self
-
end
-
-
1
def package_name
-
4
@version ? "#{@name}-#{@version}" : @name
-
end
-
-
1
def package_dir_path
-
1
"#{package_dir}/#{package_name}"
-
end
-
-
1
def tgz_file
-
1
"#{package_name}.tgz"
-
end
-
-
1
def tar_gz_file
-
1
"#{package_name}.tar.gz"
-
end
-
-
1
def tar_bz2_file
-
1
"#{package_name}.tar.bz2"
-
end
-
-
1
def zip_file
-
"#{package_name}.zip"
-
end
-
end
-
-
end
-
1
require 'rake'
-
-
1
module Rake
-
-
# Base class for Task Libraries.
-
1
class TaskLib
-
1
include Cloneable
-
1
include Rake::DSL
-
-
# Make a symbol by pasting two strings together.
-
#
-
# NOTE: DEPRECATED! This method is kinda stupid. I don't know why
-
# I didn't just use string interpolation. But now other task
-
# libraries depend on this so I can't remove it without breaking
-
# other people's code. So for now it stays for backwards
-
# compatibility. BUT DON'T USE IT.
-
1
def paste(a,b) # :nodoc:
-
(a.to_s + b.to_s).intern
-
end
-
end
-
-
end
-
# encoding: utf-8
-
-
# Load the C-based binding.
-
1
begin
-
1
RUBY_VERSION =~ /(\d+.\d+)/
-
1
require "#{$1}/ruby_prof"
-
rescue LoadError
-
1
require "ruby_prof"
-
end
-
-
1
require 'ruby-prof/aggregate_call_info'
-
1
require 'ruby-prof/call_info'
-
1
require 'ruby-prof/call_info_visitor'
-
1
require 'ruby-prof/compatibility'
-
1
require 'ruby-prof/method_info'
-
1
require 'ruby-prof/profile'
-
1
require 'ruby-prof/rack'
-
-
1
require 'ruby-prof/printers/abstract_printer'
-
1
require 'ruby-prof/printers/call_info_printer'
-
1
require 'ruby-prof/printers/call_stack_printer'
-
1
require 'ruby-prof/printers/call_tree_printer'
-
1
require 'ruby-prof/printers/dot_printer'
-
1
require 'ruby-prof/printers/flat_printer'
-
1
require 'ruby-prof/printers/flat_printer_with_line_numbers'
-
1
require 'ruby-prof/printers/graph_html_printer'
-
1
require 'ruby-prof/printers/graph_printer'
-
1
require 'ruby-prof/printers/multi_printer'
-
-
1
module RubyProf
-
# Checks if the user specified the clock mode via
-
# the RUBY_PROF_MEASURE_MODE environment variable
-
1
def self.figure_measure_mode
-
1
case ENV["RUBY_PROF_MEASURE_MODE"]
-
when "wall" || "wall_time"
-
RubyProf.measure_mode = RubyProf::WALL_TIME
-
when "cpu" || "cpu_time"
-
if ENV.key?("RUBY_PROF_CPU_FREQUENCY")
-
RubyProf.cpu_frequency = ENV["RUBY_PROF_CPU_FREQUENCY"].to_f
-
else
-
begin
-
open("/proc/cpuinfo") do |f|
-
f.each_line do |line|
-
s = line.slice(/cpu MHz\s*:\s*(.*)/, 1)
-
if s
-
RubyProf.cpu_frequency = s.to_f * 1000000
-
break
-
end
-
end
-
end
-
rescue Errno::ENOENT
-
end
-
end
-
RubyProf.measure_mode = RubyProf::CPU_TIME
-
when "allocations"
-
RubyProf.measure_mode = RubyProf::ALLOCATIONS
-
when "memory"
-
RubyProf.measure_mode = RubyProf::MEMORY
-
else
-
# the default...
-
1
RubyProf.measure_mode = RubyProf::PROCESS_TIME
-
end
-
end
-
end
-
-
1
RubyProf::figure_measure_mode
-
# encoding: utf-8
-
-
1
module RubyProf
-
1
class AggregateCallInfo
-
1
attr_reader :call_infos
-
-
1
def initialize(call_infos)
-
if call_infos.length == 0
-
raise(ArgumentError, "Must specify at least one call info.")
-
end
-
@call_infos = call_infos
-
end
-
-
1
def target
-
call_infos.first.target
-
end
-
-
1
def parent
-
call_infos.first.parent
-
end
-
-
1
def line
-
call_infos.first.line
-
end
-
-
1
def children
-
call_infos.inject(Array.new) do |result, call_info|
-
result.concat(call_info.children)
-
end
-
end
-
-
1
def total_time
-
aggregate_without_recursion(:total_time)
-
end
-
-
1
def self_time
-
aggregate_without_recursion(:self_time)
-
end
-
-
1
def wait_time
-
aggregate_without_recursion(:wait_time)
-
end
-
-
1
def children_time
-
aggregate_without_recursion(:children_time)
-
end
-
-
1
def called
-
aggregate(:called)
-
end
-
-
1
def to_s
-
"#{call_infos.first.target.full_name}"
-
end
-
-
1
private
-
-
1
def aggregate(method_name)
-
self.call_infos.inject(0) do |sum, call_info|
-
sum += call_info.send(method_name)
-
sum
-
end
-
end
-
-
1
def aggregate_without_recursion(method_name)
-
self.call_infos.inject(0) do |sum, call_info|
-
sum += call_info.send(method_name) unless call_info.recursive
-
sum
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
module RubyProf
-
1
class CallInfo
-
1
attr_accessor :recursive
-
-
1
def children_time
-
children.inject(0) do |sum, call_info|
-
sum += call_info.total_time
-
end
-
end
-
-
1
def stack
-
@stack ||= begin
-
methods = Array.new
-
call_info = self
-
-
while call_info
-
methods << call_info.target
-
call_info = call_info.parent
-
end
-
methods.reverse
-
end
-
end
-
-
1
def call_sequence
-
@call_sequence ||= begin
-
stack.map {|method| method.full_name}.join('->')
-
end
-
end
-
-
1
def root?
-
self.parent.nil?
-
end
-
-
1
def to_s
-
"#{self.target.full_name} (c: #{self.called}, tt: #{self.total_time}, st: #{self.self_time}, ct: #{self.children_time})"
-
end
-
-
# eliminate call info from the call tree.
-
# adds self and wait time to parent and attaches called methods to parent.
-
# merges call trees for methods called from both praent end self.
-
1
def eliminate!
-
# puts "eliminating #{self}"
-
return unless parent
-
parent.add_self_time(self)
-
parent.add_wait_time(self)
-
children.each do |kid|
-
if call = parent.find_call(kid)
-
call.merge_call_tree(kid)
-
else
-
parent.children << kid
-
# $stderr.puts "setting parent of #{kid}\nto #{parent}"
-
kid.parent = parent
-
end
-
end
-
parent.children.delete(self)
-
end
-
-
# find a sepcific call in list of children. returns nil if not found.
-
# note: there can't be more than one child with a given target method. in other words:
-
# x.children.grep{|y|y.target==m}.size <= 1 for all method infos m and call infos x
-
1
def find_call(other)
-
matching = children.select { |kid| kid.target == other.target }
-
raise "inconsistent call tree" unless matching.size <= 1
-
matching.first
-
end
-
-
# merge two call trees. adds self, wait, and total time of other to self and merges children of other into children of self.
-
1
def merge_call_tree(other)
-
# $stderr.puts "merging #{self}\nand #{other}"
-
self.called += other.called
-
add_self_time(other)
-
add_wait_time(other)
-
add_total_time(other)
-
other.children.each do |other_kid|
-
if kid = find_call(other_kid)
-
# $stderr.puts "merging kids"
-
kid.merge_call_tree(other_kid)
-
else
-
other_kid.parent = self
-
children << other_kid
-
end
-
end
-
other.children.clear
-
other.target.call_infos.delete(other)
-
end
-
end
-
end
-
# The call info visitor class does a depth-first traversal
-
# across a thread's call stack. At each call_info node,
-
# the visitor executes the block provided in the
-
# #visit method. The block is passed two parameters, the
-
# event and the call_info instance. Event will be
-
# either :enter or :exit.
-
#
-
# visitor = RubyProf::CallInfoVisitor.new(result.threads.first)
-
#
-
# method_names = Array.new
-
#
-
# visitor.visit do |call_info, event|
-
# method_names << call_info.target.full_name if event == :enter
-
# end
-
#
-
# puts method_names
-
-
1
module RubyProf
-
1
class CallInfoVisitor
-
1
attr_reader :block, :thread
-
-
1
def initialize(thread)
-
@thread = thread
-
end
-
-
1
def visit(&block)
-
@block = block
-
-
self.thread.top_method.call_infos.each do |call_info|
-
self.visit_call_info(call_info)
-
end
-
end
-
-
1
def visit_call_info(call_info)
-
self.block.call(call_info, :enter)
-
call_info.children.each do |child|
-
visit_call_info(child)
-
end
-
self.block.call(call_info, :exit)
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
module RubyProf
-
1
class MethodInfo
-
1
include Comparable
-
-
1
def <=>(other)
-
if self.total_time < other.total_time
-
-1
-
elsif self.total_time > other.total_time
-
1
-
elsif self.min_depth < other.min_depth
-
1
-
elsif self.min_depth > other.min_depth
-
-1
-
else
-
-1 * (self.full_name <=> other.full_name)
-
end
-
end
-
-
1
def called
-
@called ||= begin
-
call_infos.inject(0) do |sum, call_info|
-
sum += call_info.called
-
end
-
end
-
end
-
-
1
def total_time
-
@total_time ||= begin
-
call_infos.inject(0) do |sum, call_info|
-
sum += call_info.total_time unless call_info.recursive
-
sum
-
end
-
end
-
end
-
-
1
def self_time
-
@self_time ||= begin
-
call_infos.inject(0) do |sum, call_info|
-
sum += call_info.self_time unless call_info.recursive
-
sum
-
end
-
end
-
end
-
-
1
def wait_time
-
@wait_time ||= begin
-
call_infos.inject(0) do |sum, call_info|
-
sum += call_info.wait_time unless call_info.recursive
-
sum
-
end
-
end
-
end
-
-
1
def children_time
-
@children_time ||= begin
-
call_infos.inject(0) do |sum, call_info|
-
sum += call_info.children_time unless call_info.recursive
-
sum
-
end
-
end
-
end
-
-
1
def min_depth
-
@min_depth ||= call_infos.map do |call_info|
-
call_info.depth
-
end.min
-
end
-
-
1
def root?
-
@root ||= begin
-
call_infos.find do |call_info|
-
not call_info.root?
-
end.nil?
-
end
-
end
-
-
1
def recursive?
-
call_infos.detect do |call_info|
-
call_info.recursive
-
end
-
end
-
-
1
def children
-
@children ||= begin
-
call_infos.map do |call_info|
-
call_info.children
-
end.flatten
-
end
-
end
-
-
1
def aggregate_parents
-
# Group call info's based on their parents
-
groups = self.call_infos.inject(Hash.new) do |hash, call_info|
-
key = call_info.parent ? call_info.parent.target : self
-
(hash[key] ||= []) << call_info
-
hash
-
end
-
-
groups.map do |key, value|
-
AggregateCallInfo.new(value)
-
end
-
end
-
-
1
def aggregate_children
-
# Group call info's based on their targets
-
groups = self.children.inject(Hash.new) do |hash, call_info|
-
key = call_info.target
-
(hash[key] ||= []) << call_info
-
hash
-
end
-
-
groups.map do |key, value|
-
AggregateCallInfo.new(value)
-
end
-
end
-
-
1
def to_s
-
"#{self.full_name} (c: #{self.called}, tt: #{self.total_time}, st: #{self.self_time}, ct: #{self.children_time})"
-
end
-
-
# remove method from the call graph. should not be called directly.
-
1
def eliminate!
-
# $stderr.puts "eliminating #{self}"
-
call_infos.each{ |call_info| call_info.eliminate! }
-
call_infos.clear
-
end
-
-
end
-
end
-
# encoding: utf-8
-
-
1
module RubyProf
-
1
class AbstractPrinter
-
# Create a new printer.
-
#
-
# result should be the output generated from a profiling run
-
1
def initialize(result)
-
@result = result
-
@output = nil
-
end
-
-
# Specify print options.
-
#
-
# options - Hash table
-
# :min_percent - Number 0 to 100 that specifes the minimum
-
# %self (the methods self time divided by the
-
# overall total time) that a method must take
-
# for it to be printed out in the report.
-
# Default value is 0.
-
#
-
# :print_file - True or false. Specifies if a method's source
-
# file should be printed. Default value if false.
-
#
-
# :sort_method - Specifies method used for sorting method infos.
-
# Available values are :total_time, :self_time,
-
# :wait_time, :children_time
-
# Default value is :total_time
-
1
def setup_options(options = {})
-
@options = options
-
end
-
-
1
def min_percent
-
@options[:min_percent] || 0
-
end
-
-
1
def print_file
-
@options[:print_file] || false
-
end
-
-
1
def sort_method
-
@options[:sort_method] || :total_time
-
end
-
-
1
def method_name(method)
-
name = method.full_name
-
if print_file
-
name += " (#{method.source_file}:#{method.line}}"
-
end
-
name
-
end
-
-
# Print a profiling report to the provided output.
-
#
-
# output - Any IO object, including STDOUT or a file.
-
# The default value is STDOUT.
-
#
-
# options - Hash of print options. See #setup_options
-
# for more information. Note that each printer can
-
# define its own set of options.
-
1
def print(output = STDOUT, options = {})
-
@output = output
-
setup_options(options)
-
print_threads
-
end
-
-
1
def print_threads
-
@result.threads.each do |thread|
-
print_thread(thread)
-
end
-
end
-
-
1
def print_thread(thread)
-
print_header(thread)
-
print_methods(thread)
-
print_footer(thread)
-
end
-
-
1
def print_header(thread)
-
end
-
-
1
def print_footer(thread)
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
module RubyProf
-
# Prints out the call graph based on CallInfo instances. This
-
# is mainly for debugging purposes as it provides access into
-
# into RubyProf's internals.
-
-
1
class CallInfoPrinter < AbstractPrinter
-
1
TIME_WIDTH = 0
-
-
1
private
-
-
1
def print_header(thread)
-
@output << "Thread ID: #{thread.id}\n"
-
@output << "Total Time: #{thread.top_method.total_time}\n"
-
@output << "Sort by: #{sort_method}\n"
-
@output << "\n"
-
end
-
-
1
def print_methods(thread)
-
visitor = CallInfoVisitor.new(thread)
-
-
visitor.visit do |call_info, event|
-
if event == :enter
-
@output << " " * call_info.depth
-
@output << call_info.target.full_name
-
@output << " ("
-
@output << "tt:#{sprintf("%#{TIME_WIDTH}.2f", call_info.total_time)}, "
-
@output << "st:#{sprintf("%#{TIME_WIDTH}.2f", call_info.self_time)}, "
-
@output << "wt:#{sprintf("%#{TIME_WIDTH}.2f", call_info.wait_time)}, "
-
@output << "ct:#{sprintf("%#{TIME_WIDTH}.2f", call_info.children_time)}, "
-
@output << "call:#{call_info.called}, "
-
@output << "rec:#{call_info.recursive}"
-
@output << ")"
-
@output << "\n"
-
end
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
require 'erb'
-
1
require 'fileutils'
-
-
1
module RubyProf
-
# prints a HTML visualization of the call tree
-
1
class CallStackPrinter < AbstractPrinter
-
1
include ERB::Util
-
-
# Specify print options.
-
#
-
# options - Hash table
-
# :min_percent - Number 0 to 100 that specifes the minimum
-
# %self (the methods self time divided by the
-
# overall total time) that a method must take
-
# for it to be printed out in the report.
-
# Default value is 0.
-
#
-
# :print_file - True or false. Specifies if a method's source
-
# file should be printed. Default value if false.
-
#
-
# :threshold - a float from 0 to 100 that sets the threshold of
-
# results displayed.
-
# Default value is 1.0
-
#
-
# :title - a String to overide the default "ruby-prof call tree"
-
# title of the report.
-
#
-
# :expansion - a float from 0 to 100 that sets the threshold of
-
# results that are expanded, if the percent_total
-
# exceeds it.
-
# Default value is 10.0
-
#
-
# :application - a String to overide the name of the application,
-
# as it appears on the report.
-
#
-
1
def print(output = STDOUT, options = {})
-
@output = output
-
setup_options(options)
-
if @graph_html = options.delete(:graph)
-
@graph_html = "file://" + @graph_html if @graph_html[0]=="/"
-
end
-
-
print_header
-
-
@overall_threads_time = @result.threads.inject(0) do |val, thread|
-
val += thread.top_method.total_time
-
end
-
-
@result.threads.each do |thread|
-
@current_thread_id = thread.id
-
@overall_time = thread.top_method.total_time
-
@output.print "<div class=\"thread\">Thread: #{thread.id} (#{"%4.2f%%" % ((@overall_time/@overall_threads_time)*100)} ~ #{@overall_time})</div>"
-
@output.print "<ul name=\"thread\">"
-
thread.methods.each do |m|
-
# $stderr.print m.dump
-
next unless m.root?
-
m.call_infos.each do |ci|
-
next unless ci.root?
-
print_stack ci, thread.top_method.total_time
-
end
-
end
-
@output.print "</ul>"
-
end
-
-
print_footer
-
-
copy_image_files
-
end
-
-
1
def print_stack(call_info, parent_time)
-
total_time = call_info.total_time
-
percent_parent = (total_time/parent_time)*100
-
percent_total = (total_time/@overall_time)*100
-
return unless percent_total > min_percent
-
color = self.color(percent_total)
-
kids = call_info.children
-
visible = percent_total >= threshold
-
expanded = percent_total >= expansion
-
display = visible ? "block" : "none"
-
@output.print "<li class=\"color#{color}\" style=\"display:#{display}\">"
-
if kids.empty?
-
@output.print "<img src=\"empty.png\">"
-
else
-
visible_children = kids.any?{|ci| (ci.total_time/@overall_time)*100 >= threshold}
-
image = visible_children ? (expanded ? "minus" : "plus") : "empty"
-
@output.print "<img class=\"toggle\" src=\"#{image}.png\">"
-
end
-
@output.printf " %4.2f%% (%4.2f%%) %s %s\n", percent_total, percent_parent, link(call_info), graph_link(call_info)
-
unless kids.empty?
-
if expanded
-
@output.print "<ul>"
-
else
-
@output.print '<ul style="display:none">'
-
end
-
kids.sort_by{|c| -c.total_time}.each do |callinfo|
-
print_stack callinfo, total_time
-
end
-
@output.print "</ul>"
-
end
-
@output.print "</li>"
-
end
-
-
1
def name(call_info)
-
method = call_info.target
-
method.full_name
-
end
-
-
1
def link(call_info)
-
method = call_info.target
-
file = File.expand_path(method.source_file)
-
if file =~ /\/ruby_runtime$/
-
h(name(call_info))
-
else
-
if RUBY_PLATFORM =~ /darwin/
-
"<a href=\"txmt://open?url=file://#{file}&line=#{method.line}\">#{h(name(call_info))}</a>"
-
else
-
"<a href=\"file://#{file}##{method.line}\">#{h(name(call_info))}</a>"
-
end
-
end
-
end
-
-
1
def graph_link(call_info)
-
total_calls = call_info.target.call_infos.inject(0){|t, ci| t += ci.called}
-
href = "#{@graph_html}##{method_href(call_info.target)}"
-
totals = @graph_html ? "<a href='#{href}'>#{total_calls}</a>" : total_calls.to_s
-
"[#{call_info.called} calls, #{totals} total]"
-
end
-
-
1
def method_href(method)
-
h(method.full_name.gsub(/[><#\.\?=:]/,"_") + "_" + @current_thread_id.to_s)
-
end
-
-
1
def total_time(call_infos)
-
sum(call_infos.map{|ci| ci.total_time})
-
end
-
-
1
def sum(a)
-
a.inject(0.0){|s,t| s+=t}
-
end
-
-
1
def dump(ci)
-
$stderr.printf "%s/%d t:%f s:%f w:%f \n", ci, ci.object_id, ci.total_time, ci.self_time, ci.wait_time
-
end
-
-
1
def color(p)
-
case i = p.to_i
-
when 0..5
-
"01"
-
when 5..10
-
"05"
-
when 100
-
"9"
-
else
-
"#{i/10}"
-
end
-
end
-
-
1
def application
-
@options[:application] || $PROGRAM_NAME
-
end
-
-
1
def arguments
-
ARGV.join(' ')
-
end
-
-
1
def title
-
@title ||= @options.delete(:title) || "ruby-prof call tree"
-
end
-
-
1
def threshold
-
@options[:threshold] || 1.0
-
end
-
-
1
def expansion
-
@options[:expansion] || 10.0
-
end
-
-
1
def copy_image_files
-
if @output.is_a?(File)
-
target_dir = File.dirname(@output.path)
-
image_dir = File.join(File.dirname(__FILE__), '..', 'images')
-
%w(empty plus minus).each do |img|
-
source_file = "#{image_dir}/#{img}.png"
-
target_file = "#{target_dir}/#{img}.png"
-
FileUtils.cp(source_file, target_file) unless File.exist?(target_file)
-
end
-
end
-
end
-
-
1
def print_header
-
@output.puts "<html><head>"
-
@output.puts '<meta http-equiv="content-type" content="text/html; charset=utf-8">'
-
@output.puts "<title>#{h title}</title>"
-
print_css
-
print_java_script
-
@output.puts '</head><body>'
-
print_title_bar
-
print_commands
-
print_help
-
end
-
-
1
def print_footer
-
@output.puts '<div id="sentinel"></div></body></html>'
-
end
-
-
1
def print_css
-
@output.puts <<-'end_css'
-
<style type="text/css">
-
<!--
-
body {
-
font-size:70%;
-
padding:0px;
-
margin:5px;
-
margin-right:0px;
-
margin-left:0px;
-
background: #ffffff;
-
}
-
ul {
-
margin-left:0px;
-
margin-top:0px;
-
margin-bottom:0px;
-
padding-left:0px;
-
list-style-type:none;
-
}
-
li {
-
margin-left:11px;
-
padding:0px;
-
white-space:nowrap;
-
border-top:1px solid #cccccc;
-
border-left:1px solid #cccccc;
-
border-bottom:none;
-
}
-
.thread {
-
margin-left:11px;
-
background:#708090;
-
padding-top:3px;
-
padding-left:12px;
-
padding-bottom:2px;
-
border-left:1px solid #CCCCCC;
-
border-top:1px solid #CCCCCC;
-
font-weight:bold;
-
}
-
.hidden {
-
display:none;
-
width:0px;
-
height:0px;
-
margin:0px;
-
padding:0px;
-
border-style:none;
-
}
-
.color01 { background:#adbdeb }
-
.color05 { background:#9daddb }
-
.color0 { background:#8d9dcb }
-
.color1 { background:#89bccb }
-
.color2 { background:#56e3e7 }
-
.color3 { background:#32cd70 }
-
.color4 { background:#a3d53c }
-
.color5 { background:#c4cb34 }
-
.color6 { background:#dcb66d }
-
.color7 { background:#cda59e }
-
.color8 { background:#be9d9c }
-
.color9 { background:#cf947a }
-
#commands {
-
font-size:10pt;
-
padding:10px;
-
margin-left:11px;
-
margin-bottom:0px;
-
margin-top:0px;
-
background:#708090;
-
border-top:1px solid #cccccc;
-
border-left:1px solid #cccccc;
-
border-bottom:none;
-
}
-
#titlebar {
-
font-size:10pt;
-
padding:10px;
-
margin-left:11px;
-
margin-bottom:0px;
-
margin-top:10px;
-
background:#8090a0;
-
border-top:1px solid #cccccc;
-
border-left:1px solid #cccccc;
-
border-bottom:none;
-
}
-
#help {
-
font-size:10pt;
-
padding:10px;
-
margin-left:11px;
-
margin-bottom:0px;
-
margin-top:0px;
-
background:#8090a0;
-
display:none;
-
border-top:1px solid #cccccc;
-
border-left:1px solid #cccccc;
-
border-bottom:none;
-
}
-
#sentinel {
-
height: 400px;
-
margin-left:11px;
-
background:#8090a0;
-
border-top:1px solid #cccccc;
-
border-left:1px solid #cccccc;
-
border-bottom:none;
-
}
-
input { margin-left:10px; }
-
-->
-
</style>
-
end_css
-
end
-
-
1
def print_java_script
-
@output.puts <<-'end_java_script'
-
<script type="text/javascript">
-
/*
-
Copyright (C) 2005,2009 Stefan Kaes
-
skaes@railsexpress.de
-
*/
-
-
function rootNode() {
-
return currentThread;
-
}
-
-
function hideUL(node) {
-
var lis = node.childNodes
-
var l = lis.length;
-
for (var i=0; i < l ; i++ ) {
-
hideLI(lis[i]);
-
}
-
}
-
-
function showUL(node) {
-
var lis = node.childNodes;
-
var l = lis.length;
-
for (var i=0; i < l ; i++ ) {
-
showLI(lis[i]);
-
}
-
}
-
-
function findUlChild(li){
-
var ul = li.childNodes[2];
-
while (ul && ul.nodeName != "UL") {
-
ul = ul.nextSibling;
-
}
-
return ul;
-
}
-
-
function isLeafNode(li) {
-
var img = li.firstChild;
-
return (img.src.indexOf('empty.png') > -1);
-
}
-
-
function hideLI(li) {
-
if (isLeafNode(li))
-
return;
-
-
var img = li.firstChild;
-
img.src = 'plus.png';
-
-
var ul = findUlChild(li);
-
if (ul) {
-
ul.style.display = 'none';
-
hideUL(ul);
-
}
-
}
-
-
function showLI(li) {
-
if (isLeafNode(li))
-
return;
-
-
var img = li.firstChild;
-
img.src = 'minus.png';
-
-
var ul = findUlChild(li);
-
if (ul) {
-
ul.style.display = 'block';
-
showUL(ul);
-
}
-
}
-
-
function toggleLI(li) {
-
var img = li.firstChild;
-
if (img.src.indexOf("minus.png")>-1)
-
hideLI(li);
-
else {
-
if (img.src.indexOf("plus.png")>-1)
-
showLI(li);
-
}
-
}
-
-
function aboveThreshold(text, threshold) {
-
var match = text.match(/\d+[.,]\d+/);
-
return (match && parseFloat(match[0].replace(/,/, '.'))>=threshold);
-
}
-
-
function setThresholdLI(li, threshold) {
-
var img = li.firstChild;
-
var text = img.nextSibling;
-
var ul = findUlChild(li);
-
-
var visible = aboveThreshold(text.nodeValue, threshold) ? 1 : 0;
-
-
var count = 0;
-
if (ul) {
-
count = setThresholdUL(ul, threshold);
-
}
-
if (count>0) {
-
img.src = 'minus.png';
-
}
-
else {
-
img.src = 'empty.png';
-
}
-
if (visible) {
-
li.style.display = 'block'
-
}
-
else {
-
li.style.display = 'none'
-
}
-
return visible;
-
}
-
-
function setThresholdUL(node, threshold) {
-
var lis = node.childNodes;
-
var l = lis.length;
-
-
var count = 0;
-
for ( var i = 0; i < l ; i++ ) {
-
count = count + setThresholdLI(lis[i], threshold);
-
}
-
-
var visible = (count > 0) ? 1 : 0;
-
if (visible) {
-
node.style.display = 'block';
-
}
-
else {
-
node.style.display = 'none';
-
}
-
return visible;
-
}
-
-
function toggleChildren(img, event) {
-
event.cancelBubble=true;
-
-
if (img.src.indexOf('empty.png') > -1)
-
return;
-
-
var minus = (img.src.indexOf('minus.png') > -1);
-
-
if (minus) {
-
img.src = 'plus.png';
-
}
-
else
-
img.src = 'minus.png';
-
-
var li = img.parentNode;
-
var ul = findUlChild(li);
-
if (ul) {
-
if (minus)
-
ul.style.display = 'none';
-
else
-
ul.style.display = 'block';
-
}
-
if (minus)
-
moveSelectionIfNecessary(li);
-
}
-
-
function showChildren(li) {
-
var img = li.firstChild;
-
if (img.src.indexOf('empty.png') > -1)
-
return;
-
img.src = 'minus.png';
-
-
var ul = findUlChild(li);
-
if (ul) {
-
ul.style.display = 'block';
-
}
-
}
-
-
function setThreshold() {
-
var tv = document.getElementById("threshold").value;
-
if (tv.match(/[0-9]+([.,][0-9]+)?/)) {
-
var f = parseFloat(tv.replace(/,/, '.'));
-
var threads = document.getElementsByName("thread");
-
var l = threads.length;
-
for ( var i = 0; i < l ; i++ ) {
-
setThresholdUL(threads[i], f);
-
}
-
var p = selectedNode;
-
while (p && p.style.display=='none')
-
p=p.parentNode.parentNode;
-
if (p && p.nodeName=="LI")
-
selectNode(p);
-
}
-
else {
-
alert("Please specify a decimal number as threshold value!");
-
}
-
}
-
-
function collapseAll(event) {
-
event.cancelBubble=true;
-
var threads = document.getElementsByName("thread");
-
var l = threads.length;
-
for ( var i = 0; i < l ; i++ ) {
-
hideUL(threads[i]);
-
}
-
selectNode(rootNode(), null);
-
}
-
-
function expandAll(event) {
-
event.cancelBubble=true;
-
var threads = document.getElementsByName("thread");
-
var l = threads.length;
-
for ( var i = 0; i < l ; i++ ) {
-
showUL(threads[i]);
-
}
-
}
-
-
function toggleHelp(node) {
-
var help = document.getElementById("help");
-
if (node.value == "Show Help") {
-
node.value = "Hide Help";
-
help.style.display = 'block';
-
}
-
else {
-
node.value = "Show Help";
-
help.style.display = 'none';
-
}
-
}
-
-
var selectedNode = null;
-
var selectedColor = null;
-
var selectedThread = null;
-
-
function descendentOf(a,b){
-
while (a!=b && b!=null)
-
b=b.parentNode;
-
return (a==b);
-
}
-
-
function moveSelectionIfNecessary(node){
-
if (descendentOf(node, selectedNode))
-
selectNode(node, null);
-
}
-
-
function selectNode(node, event) {
-
if (event) {
-
event.cancelBubble = true;
-
thread = findThread(node);
-
selectThread(thread);
-
}
-
if (selectedNode) {
-
selectedNode.style.background = selectedColor;
-
}
-
selectedNode = node;
-
selectedColor = node.style.background;
-
selectedNode.style.background = "red";
-
selectedNode.scrollIntoView();
-
window.scrollBy(0,-400);
-
}
-
-
function moveUp(){
-
var p = selectedNode.previousSibling;
-
while (p && p.style.display == 'none')
-
p = p.previousSibling;
-
if (p && p.nodeName == "LI") {
-
selectNode(p, null);
-
}
-
}
-
-
function moveDown(){
-
var p = selectedNode.nextSibling;
-
while (p && p.style.display == 'none')
-
p = p.nextSibling;
-
if (p && p.nodeName == "LI") {
-
selectNode(p, null);
-
}
-
}
-
-
function moveLeft(){
-
var p = selectedNode.parentNode.parentNode;
-
if (p && p.nodeName=="LI") {
-
selectNode(p, null);
-
}
-
}
-
-
function moveRight(){
-
if (!isLeafNode(selectedNode)) {
-
showChildren(selectedNode);
-
var ul = findUlChild(selectedNode);
-
if (ul) {
-
selectNode(ul.firstChild, null);
-
}
-
}
-
}
-
-
function moveForward(){
-
if (isLeafNode(selectedNode)) {
-
var p = selectedNode;
-
while ((p.nextSibling == null || p.nextSibling.style.display=='none') && p.nodeName=="LI") {
-
p = p.parentNode.parentNode;
-
}
-
if (p.nodeName=="LI")
-
selectNode(p.nextSibling, null);
-
}
-
else {
-
moveRight();
-
}
-
}
-
-
function isExpandedNode(li){
-
var img = li.firstChild;
-
return(img.src.indexOf('minus.png')>-1);
-
}
-
-
function moveBackward(){
-
var p = selectedNode;
-
var q = p.previousSibling;
-
while (q != null && q.style.display=='none')
-
q = q.previousSibling;
-
if (q == null) {
-
p = p.parentNode.parentNode;
-
} else {
-
while (!isLeafNode(q) && isExpandedNode(q)) {
-
q = findUlChild(q).lastChild;
-
while (q.style.display=='none')
-
q = q.previousSibling;
-
}
-
p = q;
-
}
-
if (p.nodeName=="LI")
-
selectNode(p, null);
-
}
-
-
function moveHome() {
-
selectNode(currentThread);
-
}
-
-
var currentThreadIndex = null;
-
-
function findThread(node){
-
while (node && node.parentNode.nodeName!="BODY") {
-
node = node.parentNode;
-
}
-
return node.firstChild;
-
}
-
-
function selectThread(node){
-
var threads = document.getElementsByName("thread");
-
currentThread = node;
-
for (var i=0; i<threads.length; i++) {
-
if (threads[i]==currentThread.parentNode)
-
currentThreadIndex = i;
-
}
-
}
-
-
function nextThread(){
-
var threads = document.getElementsByName("thread");
-
if (currentThreadIndex==threads.length-1)
-
currentThreadIndex = 0;
-
else
-
currentThreadIndex += 1
-
currentThread = threads[currentThreadIndex].firstChild;
-
selectNode(currentThread, null);
-
}
-
-
function previousThread(){
-
var threads = document.getElementsByName("thread");
-
if (currentThreadIndex==0)
-
currentThreadIndex = threads.length-1;
-
else
-
currentThreadIndex -= 1
-
currentThread = threads[currentThreadIndex].firstChild;
-
selectNode(currentThread, null);
-
}
-
-
function switchThread(node, event){
-
event.cancelBubble = true;
-
selectThread(node.nextSibling.firstChild);
-
selectNode(currentThread, null);
-
}
-
-
function handleKeyEvent(event){
-
var code = event.charCode ? event.charCode : event.keyCode;
-
var str = String.fromCharCode(code);
-
switch (str) {
-
case "a": moveLeft(); break;
-
case "s": moveDown(); break;
-
case "d": moveRight(); break;
-
case "w": moveUp(); break;
-
case "f": moveForward(); break;
-
case "b": moveBackward(); break;
-
case "x": toggleChildren(selectedNode.firstChild, event); break;
-
case "*": toggleLI(selectedNode); break;
-
case "n": nextThread(); break;
-
case "h": moveHome(); break;
-
case "p": previousThread(); break;
-
}
-
}
-
document.onkeypress=function(event){ handleKeyEvent(event) };
-
-
window.onload=function(){
-
var images = document.getElementsByTagName("img");
-
for (var i=0; i<images.length; i++) {
-
var img = images[i];
-
if (img.className == "toggle") {
-
img.onclick = function(event){ toggleChildren(this, event); };
-
}
-
}
-
var divs = document.getElementsByTagName("div");
-
for (i=0; i<divs.length; i++) {
-
var div = divs[i];
-
if (div.className == "thread")
-
div.onclick = function(event){ switchThread(this, event) };
-
}
-
var lis = document.getElementsByTagName("li");
-
for (var i=0; i<lis.length; i++) {
-
lis[i].onclick = function(event){ selectNode(this, event); };
-
}
-
var threads = document.getElementsByName("thread");
-
currentThreadIndex = 0;
-
currentThread = threads[0].firstChild;
-
selectNode(currentThread, null);
-
}
-
</script>
-
end_java_script
-
end
-
-
1
def print_title_bar
-
@output.puts <<-"end_title_bar"
-
<div id="titlebar">
-
Call tree for application <b>#{h application} #{h arguments}</b><br/>
-
Generated on #{Time.now} with options #{h @options.inspect}<br/>
-
</div>
-
end_title_bar
-
end
-
-
1
def print_commands
-
@output.puts <<-"end_commands"
-
<div id=\"commands\">
-
<span style=\"font-size: 11pt; font-weight: bold;\">Threshold:</span>
-
<input value=\"#{h threshold}\" size=\"3\" id=\"threshold\" type=\"text\">
-
<input value=\"Apply\" onclick=\"setThreshold();\" type=\"submit\">
-
<input value=\"Expand All\" onclick=\"expandAll(event);\" type=\"submit\">
-
<input value=\"Collapse All\" onclick=\"collapseAll(event);\" type=\"submit\">
-
<input value=\"Show Help\" onclick=\"toggleHelp(this);\" type=\"submit\">
-
</div>
-
end_commands
-
end
-
-
1
def print_help
-
@output.puts <<-'end_help'
-
<div style="display: none;" id="help">
-
<img src="empty.png"> Enter a decimal value <i>d</i> into the threshold field and click "Apply"
-
to hide all nodes marked with time values lower than <i>d</i>.<br>
-
<img src="empty.png"> Click on "Expand All" for full tree expansion.<br>
-
<img src="empty.png"> Click on "Collapse All" to show only top level nodes.<br>
-
<img src="empty.png"> Use a, s, d, w as in Quake or Urban Terror to navigate the tree.<br>
-
<img src="empty.png"> Use f and b to navigate the tree in preorder forward and backwards.<br>
-
<img src="empty.png"> Use x to toggle visibility of a subtree.<br>
-
<img src="empty.png"> Use * to expand/collapse a whole subtree.<br>
-
<img src="empty.png"> Use h to navigate to thread root.<br>
-
<img src="empty.png"> Use n and p to navigate between threads.<br>
-
<img src="empty.png"> Click on background to move focus to a subtree.<br>
-
</div>
-
end_help
-
end
-
end
-
end
-
-
# encoding: utf-8
-
-
1
module RubyProf
-
# Generate profiling information in calltree format
-
# for use by kcachegrind and similar tools.
-
-
1
class CallTreePrinter < AbstractPrinter
-
# Specify print options.
-
#
-
# options - Hash table
-
# :min_percent - Number 0 to 100 that specifes the minimum
-
# %self (the methods self time divided by the
-
# overall total time) that a method must take
-
# for it to be printed out in the report.
-
# Default value is 0.
-
#
-
# :print_file - True or false. Specifies if a method's source
-
# file should be printed. Default value if false.
-
#
-
1
def print(output = STDOUT, options = {})
-
@output = output
-
setup_options(options)
-
-
# add a header - this information is somewhat arbitrary
-
@output << "events: "
-
case RubyProf.measure_mode
-
when RubyProf::PROCESS_TIME
-
@value_scale = RubyProf::CLOCKS_PER_SEC;
-
@output << 'process_time'
-
when RubyProf::WALL_TIME
-
@value_scale = 1_000_000
-
@output << 'wall_time'
-
when RubyProf.const_defined?(:CPU_TIME) && RubyProf::CPU_TIME
-
@value_scale = RubyProf.cpu_frequency
-
@output << 'cpu_time'
-
when RubyProf.const_defined?(:ALLOCATIONS) && RubyProf::ALLOCATIONS
-
@value_scale = 1
-
@output << 'allocations'
-
when RubyProf.const_defined?(:MEMORY) && RubyProf::MEMORY
-
@value_scale = 1
-
@output << 'memory'
-
when RubyProf.const_defined?(:GC_RUNS) && RubyProf::GC_RUNS
-
@value_scale = 1
-
@output << 'gc_runs'
-
when RubyProf.const_defined?(:GC_TIME) && RubyProf::GC_TIME
-
@value_scale = 1000000
-
@output << 'gc_time'
-
else
-
raise "Unknown measure mode: #{RubyProf.measure_mode}"
-
end
-
@output << "\n\n"
-
-
print_threads
-
end
-
-
1
def print_threads
-
@result.threads.each do |thread|
-
print_thread(thread)
-
end
-
end
-
-
1
def convert(value)
-
(value * @value_scale).round
-
end
-
-
1
def file(method)
-
File.expand_path(method.source_file)
-
end
-
-
1
def print_thread(thread)
-
thread.methods.reverse_each do |method|
-
# Print out the file and method name
-
@output << "fl=#{file(method)}\n"
-
@output << "fn=#{method_name(method)}\n"
-
-
# Now print out the function line number and its self time
-
@output << "#{method.line} #{convert(method.self_time)}\n"
-
-
# Now print out all the children methods
-
method.children.each do |callee|
-
@output << "cfl=#{file(callee.target)}\n"
-
@output << "cfn=#{method_name(callee.target)}\n"
-
@output << "calls=#{callee.called} #{callee.line}\n"
-
-
# Print out total times here!
-
@output << "#{callee.line} #{convert(callee.total_time)}\n"
-
end
-
@output << "\n"
-
end
-
end #end print_methods
-
end # end class
-
end # end packages
-
# encoding: utf-8
-
-
1
require 'set'
-
-
1
module RubyProf
-
# Generates a graphviz graph in dot format.
-
# To use the dot printer:
-
#
-
# result = RubyProf.profile do
-
# [code to profile]
-
# end
-
#
-
# printer = RubyProf::DotPrinter.new(result)
-
# printer.print(STDOUT)
-
#
-
# You can use either dot viewer such as GraphViz, or the dot command line tool
-
# to reformat the output into a wide variety of outputs:
-
#
-
# dot -Tpng graph.dot > graph.png
-
#
-
1
class DotPrinter < RubyProf::AbstractPrinter
-
1
CLASS_COLOR = '"#666666"'
-
1
EDGE_COLOR = '"#666666"'
-
-
# Creates the DotPrinter using a RubyProf::Result.
-
1
def initialize(result)
-
super(result)
-
@seen_methods = Set.new
-
end
-
-
# Print a graph report to the provided output.
-
#
-
# output - Any IO object, including STDOUT or a file. The default value is
-
# STDOUT.
-
#
-
# options - Hash of print options. See #setup_options
-
# for more information.
-
#
-
# When profiling results that cover a large number of method calls it
-
# helps to use the :min_percent option, for example:
-
#
-
# DotPrinter.new(result).print(STDOUT, :min_percent=>5)
-
#
-
1
def print(output = STDOUT, options = {})
-
@output = output
-
setup_options(options)
-
-
puts 'digraph "Profile" {'
-
#puts "label=\"#{mode_name} >=#{min_percent}%\\nTotal: #{total_time}\";"
-
puts "labelloc=t;"
-
puts "labeljust=l;"
-
print_threads
-
puts '}'
-
end
-
-
1
private
-
-
# Something of a hack, figure out which constant went with the
-
# RubyProf.measure_mode so that we can display it. Otherwise it's easy to
-
# forget what measurement was made.
-
1
def mode_name
-
RubyProf.constants.find{|c| RubyProf.const_get(c) == RubyProf.measure_mode}
-
end
-
-
1
def print_threads
-
@result.threads.each do |thread|
-
puts "subgraph \"Thread #{thread.id}\" {"
-
-
print_thread(thread)
-
puts "}"
-
-
print_classes(thread)
-
end
-
end
-
-
# Determines an ID to use to represent the subject in the Dot file.
-
1
def dot_id(subject)
-
subject.object_id
-
end
-
-
1
def print_thread(thread)
-
total_time = thread.top_method.total_time
-
thread.methods.sort_by(&sort_method).reverse_each do |method|
-
total_percentage = (method.total_time/total_time) * 100
-
-
next if total_percentage < min_percent
-
name = method_name(method).split("#").last
-
puts "#{dot_id(method)} [label=\"#{name}\\n(#{total_percentage.round}%)\"];"
-
@seen_methods << method
-
print_edges(total_time, method)
-
end
-
end
-
-
1
def print_classes(thread)
-
grouped = {}
-
thread.methods.each{|m| grouped[m.klass_name] ||= []; grouped[m.klass_name] << m}
-
grouped.each do |cls, methods2|
-
# Filter down to just seen methods
-
big_methods, small_methods = methods2.partition{|m| @seen_methods.include? m}
-
-
if !big_methods.empty?
-
puts "subgraph cluster_#{cls.object_id} {"
-
puts "label = \"#{cls}\";"
-
puts "fontcolor = #{CLASS_COLOR};"
-
puts "fontsize = 16;"
-
puts "color = #{CLASS_COLOR};"
-
big_methods.each do |m|
-
puts "#{m.object_id};"
-
end
-
puts "}"
-
end
-
end
-
end
-
-
1
def print_edges(total_time, method)
-
method.aggregate_children.sort_by(&:total_time).reverse.each do |child|
-
-
target_percentage = (child.target.total_time / total_time) * 100.0
-
next if target_percentage < min_percent
-
-
# Get children method
-
puts "#{dot_id(method)} -> #{dot_id(child.target)} [label=\"#{child.called}/#{child.target.called}\" fontsize=10 fontcolor=#{EDGE_COLOR}];"
-
end
-
end
-
-
# Silly little helper for printing to the @output
-
1
def puts(str)
-
@output.puts(str)
-
end
-
-
end
-
end
-
# encoding: utf-8
-
-
1
module RubyProf
-
# Generates flat[link:files/examples/flat_txt.html] profile reports as text.
-
# To use the flat printer:
-
#
-
# result = RubyProf.profile do
-
# [code to profile]
-
# end
-
#
-
# printer = RubyProf::FlatPrinter.new(result)
-
# printer.print(STDOUT, {})
-
#
-
1
class FlatPrinter < AbstractPrinter
-
# Override for this printer to sort by self time by default
-
1
def sort_method
-
@options[:sort_method] || :self_time
-
end
-
-
1
private
-
-
#def print_threads
-
# @result.threads.each do |thread|
-
# print_thread(thread)
-
# @output << "\n" * 2
-
# end
-
#end
-
-
1
def print_header(thread)
-
@output << "Thread ID: %d\n" % thread.id
-
@output << "Total: %0.6f\n" % thread.top_method.total_time
-
@output << "Sort by: #{sort_method}\n"
-
@output << "\n"
-
@output << " %self total self wait child calls name\n"
-
end
-
-
1
def print_methods(thread)
-
total_time = thread.top_method.total_time
-
methods = thread.methods.sort_by(&sort_method).reverse
-
-
sum = 0
-
methods.each do |method|
-
self_percent = (method.self_time / total_time) * 100
-
next if self_percent < min_percent
-
-
sum += method.self_time
-
#self_time_called = method.called > 0 ? method.self_time/method.called : 0
-
#total_time_called = method.called > 0? method.total_time/method.called : 0
-
-
@output << "%6.2f %8.2f %8.2f %8.2f %8.2f %8d %s%s \n" % [
-
method.self_time / total_time * 100, # %self
-
method.total_time, # total
-
method.self_time, # self
-
method.wait_time, # wait
-
method.children_time, # children
-
method.called, # calls
-
method.recursive? ? "*" : " ", # cycle
-
method_name(method) # name
-
]
-
end
-
end
-
-
1
def print_footer(thread)
-
@output << "\n"
-
@output << "* indicates recursively called methods\n"
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
module RubyProf
-
# Generates flat[link:files/examples/flat_txt.html] profile reports as text.
-
# To use the flat printer with line numbers:
-
#
-
# result = RubyProf.profile do
-
# [code to profile]
-
# end
-
#
-
# printer = RubyProf::FlatPrinterWithLineNumbers.new(result)
-
# printer.print(STDOUT, {})
-
#
-
1
class FlatPrinterWithLineNumbers < FlatPrinter
-
1
def print_methods(thread)
-
total_time = thread.top_method.total_time
-
-
methods = thread.methods.sort_by(&sort_method).reverse
-
sum = 0
-
methods.each do |method|
-
self_percent = (method.self_time / total_time) * 100
-
next if self_percent < min_percent
-
-
sum += method.self_time
-
#self_time_called = method.called > 0 ? method.self_time/method.called : 0
-
#total_time_called = method.called > 0? method.total_time/method.called : 0
-
-
@output << "%6.2f %8.2f %8.2f %8.2f %8.2f %8d %s%s \n" % [
-
method.self_time / total_time * 100, # %self
-
method.total_time, # total
-
method.self_time, # self
-
method.wait_time, # wait
-
method.children_time, # children
-
method.called, # calls
-
method.recursive? ? "*" : " ", # cycle
-
method_name(method) # name
-
]
-
if method.source_file != 'ruby_runtime'
-
@output << " %s:%s" % [File.expand_path(method.source_file), method.line]
-
end
-
@output << "\n\tcalled from: "
-
-
# make sure they're unique
-
method.call_infos.map{|ci|
-
if ci.parent && ci.parent.target.source_file != 'ruby_runtime'
-
[method_name(ci.parent.target), File.expand_path(ci.parent.target.source_file), ci.parent.target.line]
-
else
-
nil
-
end
-
}.compact.uniq.each{|args|
-
@output << " %s (%s:%s) " % args
-
}
-
@output << "\n\n"
-
end
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
require 'erb'
-
-
1
module RubyProf
-
# Generates graph[link:files/examples/graph_html.html] profile reports as html.
-
# To use the graph html printer:
-
#
-
# result = RubyProf.profile do
-
# [code to profile]
-
# end
-
#
-
# printer = RubyProf::GraphHtmlPrinter.new(result)
-
# printer.print(STDOUT, :min_percent=>0)
-
#
-
# The Graph printer takes the following options in its print methods:
-
# :filename - specify a file to use that contains the ERB
-
# template to use, instead of the built-in self.template
-
#
-
# :template - specify an ERB template to use, instead of the
-
# built-in self.template
-
#
-
-
1
class GraphHtmlPrinter < AbstractPrinter
-
1
include ERB::Util
-
-
1
PERCENTAGE_WIDTH = 8
-
1
TIME_WIDTH = 10
-
1
CALL_WIDTH = 20
-
-
1
def setup_options(options)
-
super(options)
-
-
filename = options[:filename]
-
template = filename ? File.read(filename).untaint : (options[:template] || self.template)
-
@erb = ERB.new(template, nil, nil)
-
@erb.filename = filename
-
end
-
-
1
def print(output = STDOUT, options = {})
-
@output = output
-
setup_options(options)
-
_erbout = @output
-
@output << @erb.result(binding)
-
end
-
-
# Creates a link to a method. Note that we do not create
-
# links to methods which are under the min_perecent
-
# specified by the user, since they will not be
-
# printed out.
-
1
def create_link(thread, method)
-
overall_time = thread.top_method.total_time
-
total_percent = (method.total_time/overall_time) * 100
-
if total_percent < min_percent
-
# Just return name
-
h method.full_name
-
else
-
href = '#' + method_href(thread, method)
-
"<a href=\"#{href}\">#{h method.full_name}</a>"
-
end
-
end
-
-
1
def method_href(thread, method)
-
h(method.full_name.gsub(/[><#\.\?=:]/,"_") + "_" + thread.id.to_s)
-
end
-
-
1
def file_link(path, linenum)
-
srcfile = File.expand_path(path)
-
if srcfile =~ /\/ruby_runtime$/
-
""
-
else
-
if RUBY_PLATFORM =~ /darwin/
-
"<a href=\"txmt://open?url=file://#{h srcfile}&line=#{linenum}\" title=\"#{h srcfile}:#{linenum}\">#{linenum}</a>"
-
else
-
"<a href=\"file://#{h srcfile}##{linenum}\" title=\"#{h srcfile}:#{linenum}\">#{linenum}</a>"
-
end
-
end
-
end
-
-
1
def template
-
'
-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
-
<html>
-
<head>
-
<style media="all" type="text/css">
-
table {
-
border-collapse: collapse;
-
border: 1px solid #CCC;
-
font-family: Verdana, Arial, Helvetica, sans-serif;
-
font-size: 9pt;
-
line-height: normal;
-
width: 100%;
-
}
-
-
th {
-
text-align: center;
-
border-top: 1px solid #FB7A31;
-
border-bottom: 1px solid #FB7A31;
-
background: #FFC;
-
padding: 0.3em;
-
border-left: 1px solid silver;
-
}
-
-
tr.break td {
-
border: 0;
-
border-top: 1px solid #FB7A31;
-
padding: 0;
-
margin: 0;
-
}
-
-
tr.method td {
-
font-weight: bold;
-
}
-
-
td {
-
padding: 0.3em;
-
}
-
-
td:first-child {
-
width: 190px;
-
}
-
-
td {
-
border-left: 1px solid #CCC;
-
text-align: center;
-
}
-
-
.method_name {
-
text-align: left;
-
}
-
-
tfoot td {
-
text-align: left;
-
}
-
</style>
-
</head>
-
<body>
-
<h1>Profile Report</h1>
-
<!-- Threads Table -->
-
<table>
-
<tr>
-
<th>Thread ID</th>
-
<th>Total Time</th>
-
</tr>
-
<% for thread in @result.threads %>
-
<tr>
-
<td><a href="#<%= thread.id %>"><%= thread.id %></a></td>
-
<td><%= thread.top_method.total_time %></td>
-
</tr>
-
<% end %>
-
</table>
-
-
<!-- Methods Tables -->
-
<% for thread in @result.threads
-
methods = thread.methods
-
total_time = thread.top_method.total_time %>
-
<h2><a name="<%= thread.id %>">Thread <%= thread.id %></a></h2>
-
-
<table>
-
<thead>
-
<tr>
-
<th><%= sprintf("%#{PERCENTAGE_WIDTH}s", "%Total") %></th>
-
<th><%= sprintf("%#{PERCENTAGE_WIDTH}s", "%Self") %></th>
-
<th><%= sprintf("%#{TIME_WIDTH}s", "Total") %></th>
-
<th><%= sprintf("%#{TIME_WIDTH}s", "Self") %></th>
-
<th><%= sprintf("%#{TIME_WIDTH}s", "Wait") %></th>
-
<th><%= sprintf("%#{TIME_WIDTH+2}s", "Child") %></th>
-
<th><%= sprintf("%#{CALL_WIDTH}s", "Calls") %></th>
-
<th class="method_name">Name</th>
-
<th>Line</th>
-
</tr>
-
</thead>
-
-
<tbody>
-
<% min_time = @options[:min_time] || (@options[:nonzero] ? 0.005 : nil)
-
methods.sort_by(&sort_method).reverse_each do |method|
-
total_percentage = (method.total_time/total_time) * 100
-
next if total_percentage < min_percent
-
next if min_time && method.total_time < min_time
-
self_percentage = (method.self_time/total_time) * 100 %>
-
-
<!-- Parents -->
-
<% for caller in method.aggregate_parents.sort_by(&:total_time)
-
next unless caller.parent
-
next if min_time && caller.total_time < min_time %>
-
<tr>
-
<td> </td>
-
<td> </td>
-
<td><%= sprintf("%#{TIME_WIDTH}.2f", caller.total_time) %></td>
-
<td><%= sprintf("%#{TIME_WIDTH}.2f", caller.self_time) %></td>
-
<td><%= sprintf("%#{TIME_WIDTH}.2f", caller.wait_time) %></td>
-
<td><%= sprintf("%#{TIME_WIDTH}.2f", caller.children_time) %></td>
-
<% called = "#{caller.called}/#{method.called}" %>
-
<td><%= sprintf("%#{CALL_WIDTH}s", called) %></td>
-
<td class="method_name"><%= create_link(thread, caller.parent.target) %></td>
-
<td><%= file_link(caller.parent.target.source_file, caller.line) %></td>
-
</tr>
-
<% end %>
-
-
<tr class="method">
-
<td><%= sprintf("%#{PERCENTAGE_WIDTH-1}.2f\%", total_percentage) %></td>
-
<td><%= sprintf("%#{PERCENTAGE_WIDTH-1}.2f\%", self_percentage) %></td>
-
<td><%= sprintf("%#{TIME_WIDTH}.2f", method.total_time) %></td>
-
<td><%= sprintf("%#{TIME_WIDTH}.2f", method.self_time) %></td>
-
<td><%= sprintf("%#{TIME_WIDTH}.2f", method.wait_time) %></td>
-
<td><%= sprintf("%#{TIME_WIDTH}.2f", method.children_time) %></td>
-
<td><%= sprintf("%#{CALL_WIDTH}i", method.called) %></td>
-
<td class="method_name">
-
<a name="<%= method_href(thread, method) %>">
-
<%= method.recursive? ? "*" : " "%><%= h method.full_name %>
-
</a>
-
</td>
-
<td><%= file_link(method.source_file, method.line) %></td>
-
</tr>
-
-
<!-- Children -->
-
<% for callee in method.aggregate_children.sort_by(&:total_time).reverse %>
-
<% next if min_time && callee.total_time < min_time %>
-
<tr>
-
<td> </td>
-
<td> </td>
-
<td><%= sprintf("%#{TIME_WIDTH}.2f", callee.total_time) %></td>
-
<td><%= sprintf("%#{TIME_WIDTH}.2f", callee.self_time) %></td>
-
<td><%= sprintf("%#{TIME_WIDTH}.2f", callee.wait_time) %></td>
-
<td><%= sprintf("%#{TIME_WIDTH}.2f", callee.children_time) %></td>
-
<% called = "#{callee.called}/#{callee.target.called}" %>
-
<td><%= sprintf("%#{CALL_WIDTH}s", called) %></td>
-
<td class="method_name"><%= create_link(thread, callee.target) %></td>
-
<td><%= file_link(method.source_file, callee.line) %></td>
-
</tr>
-
<% end %>
-
<!-- Create divider row -->
-
<tr class="break"><td colspan="9"></td></tr>
-
<% end %>
-
</tbody>
-
<tfoot>
-
<tr>
-
<td colspan="9">* indicates recursively called methods</td>
-
</tr>
-
</tfoot>
-
</table>
-
<% end %>
-
</body>
-
</html>'
-
end
-
end
-
end
-
-
# encoding: utf-8
-
-
1
module RubyProf
-
# Generates graph[link:files/examples/graph_txt.html] profile reports as text.
-
# To use the graph printer:
-
#
-
# result = RubyProf.profile do
-
# [code to profile]
-
# end
-
#
-
# printer = RubyProf::GraphPrinter.new(result)
-
# printer.print(STDOUT, {})
-
#
-
# The constructor takes two arguments. See the README
-
-
1
class GraphPrinter < AbstractPrinter
-
1
PERCENTAGE_WIDTH = 8
-
1
TIME_WIDTH = 10
-
1
CALL_WIDTH = 17
-
-
1
private
-
-
1
def print_header(thread)
-
@output << "Thread ID: #{thread.id}\n"
-
@output << "Total Time: #{thread.top_method.total_time}\n"
-
@output << "Sort by: #{sort_method}\n"
-
@output << "\n"
-
-
# 1 is for % sign
-
@output << sprintf("%#{PERCENTAGE_WIDTH}s", "%total")
-
@output << sprintf("%#{PERCENTAGE_WIDTH}s", "%self")
-
@output << sprintf("%#{TIME_WIDTH}s", "total")
-
@output << sprintf("%#{TIME_WIDTH}s", "self")
-
@output << sprintf("%#{TIME_WIDTH}s", "wait")
-
@output << sprintf("%#{TIME_WIDTH}s", "child")
-
@output << sprintf("%#{CALL_WIDTH}s", "calls")
-
@output << " Name"
-
@output << "\n"
-
end
-
-
1
def print_methods(thread)
-
total_time = thread.top_method.total_time
-
# Sort methods from longest to shortest total time
-
methods = thread.methods.sort_by(&sort_method)
-
-
# Print each method in total time order
-
methods.reverse_each do |method|
-
total_percentage = (method.total_time/total_time) * 100
-
self_percentage = (method.self_time/total_time) * 100
-
-
next if total_percentage < min_percent
-
-
@output << "-" * 80 << "\n"
-
-
print_parents(thread, method)
-
-
# 1 is for % sign
-
@output << sprintf("%#{PERCENTAGE_WIDTH-1}.2f\%", total_percentage)
-
@output << sprintf("%#{PERCENTAGE_WIDTH-1}.2f\%", self_percentage)
-
@output << sprintf("%#{TIME_WIDTH}.2f", method.total_time)
-
@output << sprintf("%#{TIME_WIDTH}.2f", method.self_time)
-
@output << sprintf("%#{TIME_WIDTH}.2f", method.wait_time)
-
@output << sprintf("%#{TIME_WIDTH}.2f", method.children_time)
-
@output << sprintf("%#{CALL_WIDTH}i", method.called)
-
@output << sprintf(" %s", method.recursive? ? "*" : " ")
-
@output << sprintf("%s", method_name(method))
-
if print_file
-
@output << sprintf(" %s:%s", method.source_file, method.line)
-
end
-
@output << "\n"
-
-
print_children(method)
-
end
-
end
-
-
1
def print_parents(thread, method)
-
method.aggregate_parents.sort_by(&:total_time).each do |caller|
-
next unless caller.parent
-
@output << " " * 2 * PERCENTAGE_WIDTH
-
@output << sprintf("%#{TIME_WIDTH}.2f", caller.total_time)
-
@output << sprintf("%#{TIME_WIDTH}.2f", caller.self_time)
-
@output << sprintf("%#{TIME_WIDTH}.2f", caller.wait_time)
-
@output << sprintf("%#{TIME_WIDTH}.2f", caller.children_time)
-
-
call_called = "#{caller.called}/#{method.called}"
-
@output << sprintf("%#{CALL_WIDTH}s", call_called)
-
@output << sprintf(" %s", caller.parent.target.full_name)
-
@output << "\n"
-
end
-
end
-
-
1
def print_children(method)
-
method.aggregate_children.sort_by(&:total_time).reverse.each do |child|
-
# Get children method
-
-
@output << " " * 2 * PERCENTAGE_WIDTH
-
-
@output << sprintf("%#{TIME_WIDTH}.2f", child.total_time)
-
@output << sprintf("%#{TIME_WIDTH}.2f", child.self_time)
-
@output << sprintf("%#{TIME_WIDTH}.2f", child.wait_time)
-
@output << sprintf("%#{TIME_WIDTH}.2f", child.children_time)
-
-
call_called = "#{child.called}/#{child.target.called}"
-
@output << sprintf("%#{CALL_WIDTH}s", call_called)
-
@output << sprintf(" %s", child.target.full_name)
-
@output << "\n"
-
end
-
end
-
-
1
def print_footer(thread)
-
@output << "\n"
-
@output << "* indicates recursively called methods\n"
-
end
-
end
-
end
-
# encoding: utf-8
-
-
1
module RubyProf
-
# Helper class to simplify printing profiles of several types from
-
# one profiling run. Currently prints a flat profile, a callgrind
-
# profile, a call stack profile and a graph profile.
-
1
class MultiPrinter
-
1
def initialize(result)
-
@stack_printer = CallStackPrinter.new(result)
-
@graph_printer = GraphHtmlPrinter.new(result)
-
@tree_printer = CallTreePrinter.new(result)
-
@flat_printer = FlatPrinter.new(result)
-
end
-
-
# create profile files under options[:path] or the current
-
# directory. options[:profile] is used as the base name for the
-
# pofile file, defaults to "profile".
-
1
def print(options)
-
@profile = options.delete(:profile) || "profile"
-
@directory = options.delete(:path) || File.expand_path(".")
-
File.open(stack_profile, "w") do |f|
-
@stack_printer.print(f, options.merge(:graph => "#{@profile}.graph.html"))
-
end
-
File.open(graph_profile, "w") do |f|
-
@graph_printer.print(f, options)
-
end
-
File.open(tree_profile, "w") do |f|
-
@tree_printer.print(f, options)
-
end
-
File.open(flat_profile, "w") do |f|
-
@flat_printer.print(f, options)
-
end
-
end
-
-
# the name of the call stack profile file
-
1
def stack_profile
-
"#{@directory}/#{@profile}.stack.html"
-
end
-
-
# the name of the graph profile file
-
1
def graph_profile
-
"#{@directory}/#{@profile}.graph.html"
-
end
-
-
# the name of the callgrind profile file
-
1
def tree_profile
-
"#{@directory}/#{@profile}.grind.dat"
-
end
-
-
# the name of the flat profile file
-
1
def flat_profile
-
"#{@directory}/#{@profile}.flat.txt"
-
end
-
-
end
-
end
-
# encoding: utf-8
-
-
1
require 'set'
-
1
module RubyProf
-
1
class Profile
-
# This method gets called once profiling has been completed
-
# but before results are returned to the user. Thus it provides
-
# a hook to do any necessary post-processing on the call graph.
-
1
def post_process
-
self.threads.each do |thread|
-
detect_recursion(thread)
-
end
-
end
-
-
# This method detect recursive calls in the call graph.
-
1
def detect_recursion(thread)
-
visited_methods = Hash.new do |hash, key|
-
hash[key] = 0
-
end
-
-
visitor = CallInfoVisitor.new(thread)
-
visitor.visit do |call_info, event|
-
case event
-
when :enter
-
visited_methods[call_info.target] += 1
-
call_info.recursive = (visited_methods[call_info.target] > 1)
-
when :exit
-
visited_methods[call_info.target] -= 1
-
if visited_methods[call_info.target] == 0
-
visited_methods.delete(call_info.target)
-
end
-
end
-
end
-
end
-
-
# eliminate some calls from the graph by merging the information into callers.
-
# matchers can be a list of strings or regular expressions or the name of a file containing regexps.
-
1
def eliminate_methods!(matchers)
-
matchers = read_regexps_from_file(matchers) if matchers.is_a?(String)
-
eliminated = []
-
threads.each do |thread|
-
matchers.each{ |matcher| eliminated.concat(eliminate_methods(thread.methods, matcher)) }
-
end
-
eliminated
-
end
-
-
1
private
-
-
# read regexps from file
-
1
def read_regexps_from_file(file_name)
-
matchers = []
-
File.open(matchers).each_line do |l|
-
next if (l =~ /^(#.*|\s*)$/) # emtpy lines and lines starting with #
-
matchers << Regexp.new(l.strip)
-
end
-
end
-
-
# eliminate methods matching matcher
-
1
def eliminate_methods(methods, matcher)
-
eliminated = []
-
i = 0
-
while i < methods.size
-
method_info = methods[i]
-
method_name = method_info.full_name
-
if matcher === method_name
-
raise "can't eliminate root method" if method_info.root?
-
eliminated << methods.delete_at(i)
-
method_info.eliminate!
-
else
-
i += 1
-
end
-
end
-
eliminated
-
end
-
-
end
-
end
-
# encoding: utf-8
-
1
require 'tmpdir'
-
-
1
module Rack
-
1
class RubyProf
-
1
def initialize(app, options = {})
-
@app = app
-
@options = options
-
@options[:min_percent] ||= 1
-
@tmpdir = options[:path] || Dir.tmpdir
-
@printer_klasses = @options[:printers] || {::RubyProf::FlatPrinter => 'flat.txt',
-
::RubyProf::GraphPrinter => 'graph.txt',
-
::RubyProf::GraphHtmlPrinter => 'graph.html',
-
::RubyProf::CallStackPrinter => 'call_stack.html'}
-
-
@printer_klasses = @options[:printers] || {::RubyProf::FlatPrinter => 'flat.txt',
-
::RubyProf::GraphPrinter => 'graph.txt',
-
::RubyProf::GraphHtmlPrinter => 'graph.html',
-
::RubyProf::CallStackPrinter => 'call_stack.html'}
-
-
@skip_paths = options[:skip_paths] || [%r{^/assets}, %r{\.css$}, %r{\.js}, %r{\.png}, %r{\.jpeg}]
-
end
-
-
1
def call(env)
-
request = Rack::Request.new(env)
-
-
if @skip_paths.any? {|skip_path| skip_path =~ request.path}
-
@app.call(env)
-
else
-
result = nil
-
data = ::RubyProf::Profile.profile do
-
result = @app.call(env)
-
end
-
-
path = request.path.gsub('/', '-')
-
path.slice!(0)
-
-
print(data, path)
-
result
-
end
-
end
-
-
1
def print(data, path)
-
@printer_klasses.each do |printer_klass, base_name|
-
printer = printer_klass.new(data)
-
file_name = ::File.join(@tmpdir, "#{path}-#{base_name}")
-
::File.open(file_name, 'wb') do |file|
-
printer.print(file, @options)
-
end
-
end
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2005-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
# Add the directory containing this file to the start of the load path if it
-
# isn't there already.
-
$:.unshift(File.dirname(__FILE__)) unless
-
1
$:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
-
-
-
1
require 'tzinfo/ruby_core_support'
-
1
require 'tzinfo/offset_rationals'
-
1
require 'tzinfo/time_or_datetime'
-
-
1
require 'tzinfo/timezone_definition'
-
-
1
require 'tzinfo/timezone_offset_info'
-
1
require 'tzinfo/timezone_transition_info'
-
-
1
require 'tzinfo/timezone_index_definition'
-
-
1
require 'tzinfo/timezone_info'
-
1
require 'tzinfo/data_timezone_info'
-
1
require 'tzinfo/linked_timezone_info'
-
-
1
require 'tzinfo/timezone_period'
-
1
require 'tzinfo/timezone'
-
1
require 'tzinfo/info_timezone'
-
1
require 'tzinfo/data_timezone'
-
1
require 'tzinfo/linked_timezone'
-
1
require 'tzinfo/timezone_proxy'
-
-
1
require 'tzinfo/country_index_definition'
-
1
require 'tzinfo/country_info'
-
-
1
require 'tzinfo/country'
-
1
require 'tzinfo/country_timezone'
-
#--
-
# Copyright (c) 2005-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
module TZInfo
-
# Thrown by Country#get if the code given is not valid.
-
1
class InvalidCountryCode < StandardError
-
end
-
-
# An ISO 3166 country. Can be used to get a list of Timezones for a country.
-
# For example:
-
#
-
# us = Country.get('US')
-
# us.zone_identifiers
-
# us.zones
-
# us.zone_info
-
1
class Country
-
1
include Comparable
-
-
# Defined countries.
-
1
@@countries = {}
-
-
# Whether the countries index has been loaded yet.
-
1
@@index_loaded = false
-
-
# Gets a Country by its ISO 3166 code. Raises an InvalidCountryCode
-
# exception if it couldn't be found.
-
1
def self.get(identifier)
-
instance = @@countries[identifier]
-
-
unless instance
-
load_index
-
info = Indexes::Countries.countries[identifier]
-
raise InvalidCountryCode.new, 'Invalid identifier' unless info
-
instance = Country.new(info)
-
@@countries[identifier] = instance
-
end
-
-
instance
-
end
-
-
# If identifier is a CountryInfo object, initializes the Country instance,
-
# otherwise calls get(identifier).
-
1
def self.new(identifier)
-
if identifier.kind_of?(CountryInfo)
-
instance = super()
-
instance.send :setup, identifier
-
instance
-
else
-
get(identifier)
-
end
-
end
-
-
# Returns an Array of all the valid country codes.
-
1
def self.all_codes
-
load_index
-
Indexes::Countries.countries.keys
-
end
-
-
# Returns an Array of all the defined Countries.
-
1
def self.all
-
load_index
-
Indexes::Countries.countries.keys.collect {|code| get(code)}
-
end
-
-
# The ISO 3166 country code.
-
1
def code
-
@info.code
-
end
-
-
# The name of the country.
-
1
def name
-
@info.name
-
end
-
-
# Alias for name.
-
1
def to_s
-
name
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #{@info.code}>"
-
end
-
-
# Returns a frozen array of all the zone identifiers for the country. These
-
# are in an order that
-
# (1) makes some geographical sense, and
-
# (2) puts the most populous zones first, where that does not contradict (1).
-
1
def zone_identifiers
-
@info.zone_identifiers
-
end
-
1
alias zone_names zone_identifiers
-
-
# An array of all the Timezones for this country. Returns TimezoneProxy
-
# objects to avoid the overhead of loading Timezone definitions until
-
# a conversion is actually required. The Timezones are returned in an order
-
# that
-
# (1) makes some geographical sense, and
-
# (2) puts the most populous zones first, where that does not contradict (1).
-
1
def zones
-
zone_identifiers.collect {|id|
-
Timezone.get_proxy(id)
-
}
-
end
-
-
# Returns a frozen array of all the timezones for the for the country as
-
# CountryTimezone instances (containing extra information about each zone).
-
# These are in an order that
-
# (1) makes some geographical sense, and
-
# (2) puts the most populous zones first, where that does not contradict (1).
-
1
def zone_info
-
@info.zones
-
end
-
-
# Compare two Countries based on their code. Returns -1 if c is less
-
# than self, 0 if c is equal to self and +1 if c is greater than self.
-
1
def <=>(c)
-
code <=> c.code
-
end
-
-
# Returns true if and only if the code of c is equal to the code of this
-
# Country.
-
1
def eql?(c)
-
self == c
-
end
-
-
# Returns a hash value for this Country.
-
1
def hash
-
code.hash
-
end
-
-
# Dumps this Country for marshalling.
-
1
def _dump(limit)
-
code
-
end
-
-
# Loads a marshalled Country.
-
1
def self._load(data)
-
Country.get(data)
-
end
-
-
1
private
-
# Loads in the index of countries if it hasn't already been loaded.
-
1
def self.load_index
-
unless @@index_loaded
-
require 'tzinfo/indexes/countries'
-
@@index_loaded = true
-
end
-
end
-
-
# Called by Country.new to initialize a new Country instance. The info
-
# parameter is a CountryInfo that defines the country.
-
1
def setup(info)
-
@info = info
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
module TZInfo
-
# The country index file includes CountryIndexDefinition which provides
-
# a country method used to define each country in the index.
-
1
module CountryIndexDefinition #:nodoc:
-
1
def self.append_features(base)
-
super
-
base.extend(ClassMethods)
-
base.instance_eval { @countries = {} }
-
end
-
-
1
module ClassMethods #:nodoc:
-
# Defines a country with an ISO 3166 country code, name and block. The
-
# block will be evaluated to obtain all the timezones for the country.
-
# Calls Country.country_defined with the definition of each country.
-
1
def country(code, name, &block)
-
@countries[code] = CountryInfo.new(code, name, &block)
-
end
-
-
# Returns a frozen hash of all the countries that have been defined in
-
# the index.
-
1
def countries
-
@countries.freeze
-
end
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
module TZInfo
-
# Class to store the data loaded from the country index. Instances of this
-
# class are passed to the blocks in the index that define timezones.
-
1
class CountryInfo #:nodoc:
-
1
attr_reader :code
-
1
attr_reader :name
-
-
# Constructs a new CountryInfo with an ISO 3166 country code, name and
-
# block. The block will be evaluated to obtain the timezones for the country
-
# (when they are first needed).
-
1
def initialize(code, name, &block)
-
@code = code
-
@name = name
-
@block = block
-
@zones = nil
-
@zone_identifiers = nil
-
end
-
-
# Called by the index data to define a timezone for the country.
-
1
def timezone(identifier, latitude_numerator, latitude_denominator,
-
longitude_numerator, longitude_denominator, description = nil)
-
# Currently only store the identifiers.
-
@zones << CountryTimezone.new(identifier, latitude_numerator,
-
latitude_denominator, longitude_numerator, longitude_denominator,
-
description)
-
end
-
-
# Returns a frozen array of all the zone identifiers for the country. These
-
# are in the order they were added using the timezone method.
-
1
def zone_identifiers
-
unless @zone_identifiers
-
@zone_identifiers = zones.collect {|zone| zone.identifier}
-
@zone_identifiers.freeze
-
end
-
-
@zone_identifiers
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #@code>"
-
end
-
-
# Returns a frozen array of all the timezones for the for the country as
-
# CountryTimezone instances. These are in the order they were added using
-
# the timezone method.
-
1
def zones
-
unless @zones
-
@zones = []
-
@block.call(self) if @block
-
@block = nil
-
@zones.freeze
-
end
-
-
@zones
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
module TZInfo
-
# A Timezone within a Country. This contains extra information about the
-
# Timezone that is specific to the Country (a Timezone could be used by
-
# multiple countries).
-
1
class CountryTimezone
-
# The zone identifier.
-
1
attr_reader :identifier
-
-
# A description of this timezone in relation to the country, e.g.
-
# "Eastern Time". This is usually nil for countries having only a single
-
# Timezone.
-
1
attr_reader :description
-
-
# Creates a new CountryTimezone with a timezone identifier, latitude,
-
# longitude and description. The latitude and longitude are specified as
-
# rationals - a numerator and denominator. For performance reasons, the
-
# numerators and denominators must be specified in their lowest form.
-
#
-
# CountryTimezone instances should not normally be constructed manually.
-
1
def initialize(identifier, latitude_numerator, latitude_denominator,
-
longitude_numerator, longitude_denominator, description = nil) #:nodoc:
-
@identifier = identifier
-
@latitude_numerator = latitude_numerator
-
@latitude_denominator = latitude_denominator
-
@longitude_numerator = longitude_numerator
-
@longitude_denominator = longitude_denominator
-
@description = description
-
end
-
-
# The Timezone (actually a TimezoneProxy for performance reasons).
-
1
def timezone
-
Timezone.get_proxy(@identifier)
-
end
-
-
# if description is not nil, this method returns description; otherwise it
-
# returns timezone.friendly_identifier(true).
-
1
def description_or_friendly_identifier
-
description || timezone.friendly_identifier(true)
-
end
-
-
# The latitude of this timezone in degrees as a Rational.
-
1
def latitude
-
@latitude ||= RubyCoreSupport.rational_new!(@latitude_numerator, @latitude_denominator)
-
end
-
-
# The longitude of this timezone in degrees as a Rational.
-
1
def longitude
-
@longitude ||= RubyCoreSupport.rational_new!(@longitude_numerator, @longitude_denominator)
-
end
-
-
# Returns true if and only if the given CountryTimezone is equal to the
-
# current CountryTimezone (has the same identifer, latitude, longitude
-
# and description).
-
1
def ==(ct)
-
ct.respond_to?(:identifier) && ct.respond_to?(:latitude) &&
-
ct.respond_to?(:longitude) && ct.respond_to?(:description) &&
-
identifier == ct.identifier && latitude == ct.latitude &&
-
longitude == ct.longitude && description == ct.description
-
end
-
-
# Returns true if and only if the given CountryTimezone is equal to the
-
# current CountryTimezone (has the same identifer, latitude, longitude
-
# and description).
-
1
def eql?(ct)
-
self == ct
-
end
-
-
# Returns a hash of this CountryTimezone.
-
1
def hash
-
@identifier.hash ^ @latitude_numerator.hash ^ @latitude_denominator.hash ^
-
@longitude_numerator.hash ^ @longitude_denominator.hash ^ @description.hash
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #@identifier>"
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
module TZInfo
-
-
# A Timezone based on a DataTimezoneInfo.
-
1
class DataTimezone < InfoTimezone #:nodoc:
-
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
#
-
# If no TimezonePeriod could be found, PeriodNotFound is raised.
-
1
def period_for_utc(utc)
-
461
info.period_for_utc(utc)
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how abiguities should be resolved.
-
# Raises PeriodNotFound if no periods are found for the given time.
-
1
def periods_for_local(local)
-
196
info.periods_for_local(local)
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
module TZInfo
-
# Thrown if no offsets have been defined when calling period_for_utc or
-
# periods_for_local. Indicates an error in the timezone data.
-
1
class NoOffsetsDefined < StandardError
-
end
-
-
# Represents a (non-linked) timezone defined in a data module.
-
1
class DataTimezoneInfo < TimezoneInfo #:nodoc:
-
-
# Constructs a new TimezoneInfo with its identifier.
-
1
def initialize(identifier)
-
122
super(identifier)
-
122
@offsets = {}
-
122
@transitions = []
-
122
@previous_offset = nil
-
122
@transitions_index = nil
-
end
-
-
# Defines a offset. The id uniquely identifies this offset within the
-
# timezone. utc_offset and std_offset define the offset in seconds of
-
# standard time from UTC and daylight savings from standard time
-
# respectively. abbreviation describes the timezone offset (e.g. GMT, BST,
-
# EST or EDT).
-
#
-
# The first offset to be defined is treated as the offset that applies
-
# until the first transition. This will usually be in Local Mean Time (LMT).
-
#
-
# ArgumentError will be raised if the id is already defined.
-
1
def offset(id, utc_offset, std_offset, abbreviation)
-
616
raise ArgumentError, 'Offset already defined' if @offsets.has_key?(id)
-
-
616
offset = TimezoneOffsetInfo.new(utc_offset, std_offset, abbreviation)
-
616
@offsets[id] = offset
-
616
@previous_offset = offset unless @previous_offset
-
end
-
-
# Defines a transition. Transitions must be defined in chronological order.
-
# ArgumentError will be raised if a transition is added out of order.
-
# offset_id refers to an id defined with offset. ArgumentError will be
-
# raised if the offset_id cannot be found. numerator_or_time and
-
# denomiator specify the time the transition occurs as. See
-
# TimezoneTransitionInfo for more detail about specifying times.
-
1
def transition(year, month, offset_id, numerator_or_time, denominator = nil)
-
10948
offset = @offsets[offset_id]
-
10948
raise ArgumentError, 'Offset not found' unless offset
-
-
10948
if @transitions_index
-
10827
if year < @last_year || (year == @last_year && month < @last_month)
-
raise ArgumentError, 'Transitions must be increasing date order'
-
end
-
-
# Record the position of the first transition with this index.
-
10827
index = transition_index(year, month)
-
10827
@transitions_index[index] ||= @transitions.length
-
-
# Fill in any gaps
-
10827
(index - 1).downto(0) do |i|
-
27944
break if @transitions_index[i]
-
17117
@transitions_index[i] = @transitions.length
-
end
-
else
-
121
@transitions_index = [@transitions.length]
-
121
@start_year = year
-
121
@start_month = month
-
end
-
-
@transitions << TimezoneTransitionInfo.new(offset, @previous_offset,
-
10948
numerator_or_time, denominator)
-
10948
@last_year = year
-
10948
@last_month = month
-
10948
@previous_offset = offset
-
end
-
-
# Returns the TimezonePeriod for the given UTC time.
-
# Raises NoOffsetsDefined if no offsets have been defined.
-
1
def period_for_utc(utc)
-
461
unless @transitions.empty?
-
454
utc = TimeOrDateTime.wrap(utc)
-
454
index = transition_index(utc.year, utc.mon)
-
-
454
start_transition = nil
-
454
start = transition_before_end(index)
-
454
if start
-
454
start.downto(0) do |i|
-
557
if @transitions[i].at <= utc
-
454
start_transition = @transitions[i]
-
454
break
-
end
-
end
-
end
-
-
454
end_transition = nil
-
454
start = transition_after_start(index)
-
454
if start
-
282
start.upto(@transitions.length - 1) do |i|
-
465
if @transitions[i].at > utc
-
282
end_transition = @transitions[i]
-
282
break
-
end
-
end
-
end
-
-
454
if start_transition || end_transition
-
454
TimezonePeriod.new(start_transition, end_transition)
-
else
-
# Won't happen since there are transitions. Must always find one
-
# transition that is either >= or < the specified time.
-
raise 'No transitions found in search'
-
end
-
else
-
7
raise NoOffsetsDefined, 'No offsets have been defined' unless @previous_offset
-
7
TimezonePeriod.new(nil, nil, @previous_offset)
-
end
-
end
-
-
# Returns the set of TimezonePeriods for the given local time as an array.
-
# Results returned are ordered by increasing UTC start date.
-
# Returns an empty array if no periods are found for the given time.
-
# Raises NoOffsetsDefined if no offsets have been defined.
-
1
def periods_for_local(local)
-
196
unless @transitions.empty?
-
196
local = TimeOrDateTime.wrap(local)
-
196
index = transition_index(local.year, local.mon)
-
-
196
result = []
-
-
196
start_index = transition_after_start(index - 1)
-
196
if start_index && @transitions[start_index].local_end > local
-
5
if start_index > 0
-
3
if @transitions[start_index - 1].local_start <= local
-
3
result << TimezonePeriod.new(@transitions[start_index - 1], @transitions[start_index])
-
end
-
else
-
2
result << TimezonePeriod.new(nil, @transitions[start_index])
-
end
-
end
-
-
196
end_index = transition_before_end(index + 1)
-
-
196
if end_index
-
194
start_index = end_index unless start_index
-
-
194
start_index.upto(transition_before_end(index + 1)) do |i|
-
536
if @transitions[i].local_start <= local
-
258
if i + 1 < @transitions.length
-
240
if @transitions[i + 1].local_end > local
-
167
result << TimezonePeriod.new(@transitions[i], @transitions[i + 1])
-
end
-
else
-
18
result << TimezonePeriod.new(@transitions[i], nil)
-
end
-
end
-
end
-
end
-
-
196
result
-
else
-
raise NoOffsetsDefined, 'No offsets have been defined' unless @previous_offset
-
[TimezonePeriod.new(nil, nil, @previous_offset)]
-
end
-
end
-
-
1
private
-
# Returns the index into the @transitions_index array for a given year
-
# and month.
-
1
def transition_index(year, month)
-
11477
index = (year - @start_year) * 2
-
11477
index += 1 if month > 6
-
11477
index -= 1 if @start_month > 6
-
11477
index
-
end
-
-
# Returns the index into @transitions of the first transition that occurs
-
# on or after the start of the given index into @transitions_index.
-
# Returns nil if there are no such transitions.
-
1
def transition_after_start(index)
-
650
if index >= @transitions_index.length
-
nil
-
else
-
460
index = 0 if index < 0
-
460
@transitions_index[index]
-
end
-
end
-
-
# Returns the index into @transitions of the first transition that occurs
-
# before the end of the given index into @transitions_index.
-
# Returns nil if there are no such transitions.
-
1
def transition_before_end(index)
-
844
index = index + 1
-
-
844
if index <= 0
-
nil
-
842
elsif index >= @transitions_index.length
-
208
@transitions.length - 1
-
else
-
634
@transitions_index[index] - 1
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Africa
-
1
module Algiers
-
1
include TimezoneDefinition
-
-
1
timezone 'Africa/Algiers' do |tz|
-
1
tz.offset :o0, 732, 0, :LMT
-
1
tz.offset :o1, 561, 0, :PMT
-
1
tz.offset :o2, 0, 0, :WET
-
1
tz.offset :o3, 0, 3600, :WEST
-
1
tz.offset :o4, 3600, 0, :CET
-
1
tz.offset :o5, 3600, 3600, :CEST
-
-
1
tz.transition 1891, 3, :o1, 2170625843, 900
-
1
tz.transition 1911, 3, :o2, 69670267013, 28800
-
1
tz.transition 1916, 6, :o3, 58104707, 24
-
1
tz.transition 1916, 10, :o2, 58107323, 24
-
1
tz.transition 1917, 3, :o3, 58111499, 24
-
1
tz.transition 1917, 10, :o2, 58116227, 24
-
1
tz.transition 1918, 3, :o3, 58119899, 24
-
1
tz.transition 1918, 10, :o2, 58124963, 24
-
1
tz.transition 1919, 3, :o3, 58128467, 24
-
1
tz.transition 1919, 10, :o2, 58133699, 24
-
1
tz.transition 1920, 2, :o3, 58136867, 24
-
1
tz.transition 1920, 10, :o2, 58142915, 24
-
1
tz.transition 1921, 3, :o3, 58146323, 24
-
1
tz.transition 1921, 6, :o2, 58148699, 24
-
1
tz.transition 1939, 9, :o3, 58308443, 24
-
1
tz.transition 1939, 11, :o2, 4859173, 2
-
1
tz.transition 1940, 2, :o4, 29156215, 12
-
1
tz.transition 1944, 4, :o5, 58348405, 24
-
1
tz.transition 1944, 10, :o4, 4862743, 2
-
1
tz.transition 1945, 4, :o5, 58357141, 24
-
1
tz.transition 1945, 9, :o4, 58361147, 24
-
1
tz.transition 1946, 10, :o2, 58370411, 24
-
1
tz.transition 1956, 1, :o4, 4871003, 2
-
1
tz.transition 1963, 4, :o2, 58515203, 24
-
1
tz.transition 1971, 4, :o3, 41468400
-
1
tz.transition 1971, 9, :o2, 54774000
-
1
tz.transition 1977, 5, :o3, 231724800
-
1
tz.transition 1977, 10, :o4, 246236400
-
1
tz.transition 1978, 3, :o5, 259545600
-
1
tz.transition 1978, 9, :o4, 275274000
-
1
tz.transition 1979, 10, :o2, 309740400
-
1
tz.transition 1980, 4, :o3, 325468800
-
1
tz.transition 1980, 10, :o2, 341802000
-
1
tz.transition 1981, 5, :o4, 357523200
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Africa
-
1
module Cairo
-
1
include TimezoneDefinition
-
-
1
timezone 'Africa/Cairo' do |tz|
-
1
tz.offset :o0, 7500, 0, :LMT
-
1
tz.offset :o1, 7200, 0, :EET
-
1
tz.offset :o2, 7200, 3600, :EEST
-
-
1
tz.transition 1900, 9, :o1, 695604503, 288
-
1
tz.transition 1940, 7, :o2, 29157905, 12
-
1
tz.transition 1940, 9, :o1, 19439227, 8
-
1
tz.transition 1941, 4, :o2, 29161193, 12
-
1
tz.transition 1941, 9, :o1, 19442027, 8
-
1
tz.transition 1942, 3, :o2, 29165405, 12
-
1
tz.transition 1942, 10, :o1, 19445275, 8
-
1
tz.transition 1943, 3, :o2, 29169785, 12
-
1
tz.transition 1943, 10, :o1, 19448235, 8
-
1
tz.transition 1944, 3, :o2, 29174177, 12
-
1
tz.transition 1944, 10, :o1, 19451163, 8
-
1
tz.transition 1945, 4, :o2, 29178737, 12
-
1
tz.transition 1945, 10, :o1, 19454083, 8
-
1
tz.transition 1957, 5, :o2, 29231621, 12
-
1
tz.transition 1957, 9, :o1, 19488899, 8
-
1
tz.transition 1958, 4, :o2, 29235893, 12
-
1
tz.transition 1958, 9, :o1, 19491819, 8
-
1
tz.transition 1959, 4, :o2, 58480547, 24
-
1
tz.transition 1959, 9, :o1, 4873683, 2
-
1
tz.transition 1960, 4, :o2, 58489331, 24
-
1
tz.transition 1960, 9, :o1, 4874415, 2
-
1
tz.transition 1961, 4, :o2, 58498091, 24
-
1
tz.transition 1961, 9, :o1, 4875145, 2
-
1
tz.transition 1962, 4, :o2, 58506851, 24
-
1
tz.transition 1962, 9, :o1, 4875875, 2
-
1
tz.transition 1963, 4, :o2, 58515611, 24
-
1
tz.transition 1963, 9, :o1, 4876605, 2
-
1
tz.transition 1964, 4, :o2, 58524395, 24
-
1
tz.transition 1964, 9, :o1, 4877337, 2
-
1
tz.transition 1965, 4, :o2, 58533155, 24
-
1
tz.transition 1965, 9, :o1, 4878067, 2
-
1
tz.transition 1966, 4, :o2, 58541915, 24
-
1
tz.transition 1966, 10, :o1, 4878799, 2
-
1
tz.transition 1967, 4, :o2, 58550675, 24
-
1
tz.transition 1967, 10, :o1, 4879529, 2
-
1
tz.transition 1968, 4, :o2, 58559459, 24
-
1
tz.transition 1968, 10, :o1, 4880261, 2
-
1
tz.transition 1969, 4, :o2, 58568219, 24
-
1
tz.transition 1969, 10, :o1, 4880991, 2
-
1
tz.transition 1970, 4, :o2, 10364400
-
1
tz.transition 1970, 10, :o1, 23587200
-
1
tz.transition 1971, 4, :o2, 41900400
-
1
tz.transition 1971, 10, :o1, 55123200
-
1
tz.transition 1972, 4, :o2, 73522800
-
1
tz.transition 1972, 10, :o1, 86745600
-
1
tz.transition 1973, 4, :o2, 105058800
-
1
tz.transition 1973, 10, :o1, 118281600
-
1
tz.transition 1974, 4, :o2, 136594800
-
1
tz.transition 1974, 10, :o1, 149817600
-
1
tz.transition 1975, 4, :o2, 168130800
-
1
tz.transition 1975, 10, :o1, 181353600
-
1
tz.transition 1976, 4, :o2, 199753200
-
1
tz.transition 1976, 10, :o1, 212976000
-
1
tz.transition 1977, 4, :o2, 231289200
-
1
tz.transition 1977, 10, :o1, 244512000
-
1
tz.transition 1978, 4, :o2, 262825200
-
1
tz.transition 1978, 10, :o1, 276048000
-
1
tz.transition 1979, 4, :o2, 294361200
-
1
tz.transition 1979, 10, :o1, 307584000
-
1
tz.transition 1980, 4, :o2, 325983600
-
1
tz.transition 1980, 10, :o1, 339206400
-
1
tz.transition 1981, 4, :o2, 357519600
-
1
tz.transition 1981, 10, :o1, 370742400
-
1
tz.transition 1982, 7, :o2, 396399600
-
1
tz.transition 1982, 10, :o1, 402278400
-
1
tz.transition 1983, 7, :o2, 426812400
-
1
tz.transition 1983, 10, :o1, 433814400
-
1
tz.transition 1984, 4, :o2, 452214000
-
1
tz.transition 1984, 10, :o1, 465436800
-
1
tz.transition 1985, 4, :o2, 483750000
-
1
tz.transition 1985, 10, :o1, 496972800
-
1
tz.transition 1986, 4, :o2, 515286000
-
1
tz.transition 1986, 10, :o1, 528508800
-
1
tz.transition 1987, 4, :o2, 546822000
-
1
tz.transition 1987, 10, :o1, 560044800
-
1
tz.transition 1988, 4, :o2, 578444400
-
1
tz.transition 1988, 10, :o1, 591667200
-
1
tz.transition 1989, 5, :o2, 610412400
-
1
tz.transition 1989, 10, :o1, 623203200
-
1
tz.transition 1990, 4, :o2, 641516400
-
1
tz.transition 1990, 10, :o1, 654739200
-
1
tz.transition 1991, 4, :o2, 673052400
-
1
tz.transition 1991, 10, :o1, 686275200
-
1
tz.transition 1992, 4, :o2, 704674800
-
1
tz.transition 1992, 10, :o1, 717897600
-
1
tz.transition 1993, 4, :o2, 736210800
-
1
tz.transition 1993, 10, :o1, 749433600
-
1
tz.transition 1994, 4, :o2, 767746800
-
1
tz.transition 1994, 10, :o1, 780969600
-
1
tz.transition 1995, 4, :o2, 799020000
-
1
tz.transition 1995, 9, :o1, 812322000
-
1
tz.transition 1996, 4, :o2, 830469600
-
1
tz.transition 1996, 9, :o1, 843771600
-
1
tz.transition 1997, 4, :o2, 861919200
-
1
tz.transition 1997, 9, :o1, 875221200
-
1
tz.transition 1998, 4, :o2, 893368800
-
1
tz.transition 1998, 9, :o1, 906670800
-
1
tz.transition 1999, 4, :o2, 925423200
-
1
tz.transition 1999, 9, :o1, 938725200
-
1
tz.transition 2000, 4, :o2, 956872800
-
1
tz.transition 2000, 9, :o1, 970174800
-
1
tz.transition 2001, 4, :o2, 988322400
-
1
tz.transition 2001, 9, :o1, 1001624400
-
1
tz.transition 2002, 4, :o2, 1019772000
-
1
tz.transition 2002, 9, :o1, 1033074000
-
1
tz.transition 2003, 4, :o2, 1051221600
-
1
tz.transition 2003, 9, :o1, 1064523600
-
1
tz.transition 2004, 4, :o2, 1083276000
-
1
tz.transition 2004, 9, :o1, 1096578000
-
1
tz.transition 2005, 4, :o2, 1114725600
-
1
tz.transition 2005, 9, :o1, 1128027600
-
1
tz.transition 2006, 4, :o2, 1146175200
-
1
tz.transition 2006, 9, :o1, 1158872400
-
1
tz.transition 2007, 4, :o2, 1177624800
-
1
tz.transition 2007, 9, :o1, 1189112400
-
1
tz.transition 2008, 4, :o2, 1209074400
-
1
tz.transition 2008, 8, :o1, 1219957200
-
1
tz.transition 2009, 4, :o2, 1240524000
-
1
tz.transition 2009, 8, :o1, 1250802000
-
1
tz.transition 2010, 4, :o2, 1272578400
-
1
tz.transition 2010, 8, :o1, 1281474000
-
1
tz.transition 2010, 9, :o2, 1284069600
-
1
tz.transition 2010, 9, :o1, 1285880400
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Africa
-
1
module Casablanca
-
1
include TimezoneDefinition
-
-
1
timezone 'Africa/Casablanca' do |tz|
-
1
tz.offset :o0, -1820, 0, :LMT
-
1
tz.offset :o1, 0, 0, :WET
-
1
tz.offset :o2, 0, 3600, :WEST
-
1
tz.offset :o3, 3600, 0, :CET
-
-
1
tz.transition 1913, 10, :o1, 10454687371, 4320
-
1
tz.transition 1939, 9, :o2, 4859037, 2
-
1
tz.transition 1939, 11, :o1, 58310075, 24
-
1
tz.transition 1940, 2, :o2, 4859369, 2
-
1
tz.transition 1945, 11, :o1, 58362659, 24
-
1
tz.transition 1950, 6, :o2, 4866887, 2
-
1
tz.transition 1950, 10, :o1, 58406003, 24
-
1
tz.transition 1967, 6, :o2, 2439645, 1
-
1
tz.transition 1967, 9, :o1, 58554347, 24
-
1
tz.transition 1974, 6, :o2, 141264000
-
1
tz.transition 1974, 8, :o1, 147222000
-
1
tz.transition 1976, 5, :o2, 199756800
-
1
tz.transition 1976, 7, :o1, 207702000
-
1
tz.transition 1977, 5, :o2, 231292800
-
1
tz.transition 1977, 9, :o1, 244249200
-
1
tz.transition 1978, 6, :o2, 265507200
-
1
tz.transition 1978, 8, :o1, 271033200
-
1
tz.transition 1984, 3, :o3, 448243200
-
1
tz.transition 1985, 12, :o1, 504918000
-
1
tz.transition 2008, 6, :o2, 1212278400
-
1
tz.transition 2008, 8, :o1, 1220223600
-
1
tz.transition 2009, 6, :o2, 1243814400
-
1
tz.transition 2009, 8, :o1, 1250809200
-
1
tz.transition 2010, 5, :o2, 1272758400
-
1
tz.transition 2010, 8, :o1, 1281222000
-
1
tz.transition 2011, 4, :o2, 1301788800
-
1
tz.transition 2011, 7, :o1, 1312066800
-
1
tz.transition 2012, 4, :o2, 1335664800
-
1
tz.transition 2012, 7, :o1, 1342749600
-
1
tz.transition 2012, 8, :o2, 1345428000
-
1
tz.transition 2012, 9, :o1, 1348970400
-
1
tz.transition 2013, 4, :o2, 1367114400
-
1
tz.transition 2013, 9, :o1, 1380420000
-
1
tz.transition 2014, 4, :o2, 1398564000
-
1
tz.transition 2014, 9, :o1, 1411869600
-
1
tz.transition 2015, 4, :o2, 1430013600
-
1
tz.transition 2015, 9, :o1, 1443319200
-
1
tz.transition 2016, 4, :o2, 1461463200
-
1
tz.transition 2016, 9, :o1, 1474768800
-
1
tz.transition 2017, 4, :o2, 1493517600
-
1
tz.transition 2017, 9, :o1, 1506218400
-
1
tz.transition 2018, 4, :o2, 1524967200
-
1
tz.transition 2018, 9, :o1, 1538272800
-
1
tz.transition 2019, 4, :o2, 1556416800
-
1
tz.transition 2019, 9, :o1, 1569722400
-
1
tz.transition 2020, 4, :o2, 1587866400
-
1
tz.transition 2020, 9, :o1, 1601172000
-
1
tz.transition 2021, 4, :o2, 1619316000
-
1
tz.transition 2021, 9, :o1, 1632621600
-
1
tz.transition 2022, 4, :o2, 1650765600
-
1
tz.transition 2022, 9, :o1, 1664071200
-
1
tz.transition 2023, 4, :o2, 1682820000
-
1
tz.transition 2023, 9, :o1, 1695520800
-
1
tz.transition 2024, 4, :o2, 1714269600
-
1
tz.transition 2024, 9, :o1, 1727575200
-
1
tz.transition 2025, 4, :o2, 1745719200
-
1
tz.transition 2025, 9, :o1, 1759024800
-
1
tz.transition 2026, 4, :o2, 1777168800
-
1
tz.transition 2026, 9, :o1, 1790474400
-
1
tz.transition 2027, 4, :o2, 1808618400
-
1
tz.transition 2027, 9, :o1, 1821924000
-
1
tz.transition 2028, 4, :o2, 1840672800
-
1
tz.transition 2028, 9, :o1, 1853373600
-
1
tz.transition 2029, 4, :o2, 1872122400
-
1
tz.transition 2029, 9, :o1, 1885428000
-
1
tz.transition 2030, 4, :o2, 1903572000
-
1
tz.transition 2030, 9, :o1, 1916877600
-
1
tz.transition 2031, 4, :o2, 1935021600
-
1
tz.transition 2031, 9, :o1, 1948327200
-
1
tz.transition 2032, 4, :o2, 1966471200
-
1
tz.transition 2032, 9, :o1, 1979776800
-
1
tz.transition 2033, 4, :o2, 1997920800
-
1
tz.transition 2033, 9, :o1, 2011226400
-
1
tz.transition 2034, 4, :o2, 2029975200
-
1
tz.transition 2034, 9, :o1, 2042676000
-
1
tz.transition 2035, 4, :o2, 2061424800
-
1
tz.transition 2035, 9, :o1, 2074730400
-
1
tz.transition 2036, 4, :o2, 2092874400
-
1
tz.transition 2036, 9, :o1, 2106180000
-
1
tz.transition 2037, 4, :o2, 2124324000
-
1
tz.transition 2037, 9, :o1, 2137629600
-
1
tz.transition 2038, 4, :o2, 29586463, 12
-
1
tz.transition 2038, 9, :o1, 29588311, 12
-
1
tz.transition 2039, 4, :o2, 29590831, 12
-
1
tz.transition 2039, 9, :o1, 29592679, 12
-
1
tz.transition 2040, 4, :o2, 29595283, 12
-
1
tz.transition 2040, 9, :o1, 29597131, 12
-
1
tz.transition 2041, 4, :o2, 29599651, 12
-
1
tz.transition 2041, 9, :o1, 29601499, 12
-
1
tz.transition 2042, 4, :o2, 29604019, 12
-
1
tz.transition 2042, 9, :o1, 29605867, 12
-
1
tz.transition 2043, 4, :o2, 29608387, 12
-
1
tz.transition 2043, 9, :o1, 29610235, 12
-
1
tz.transition 2044, 4, :o2, 29612755, 12
-
1
tz.transition 2044, 9, :o1, 29614603, 12
-
1
tz.transition 2045, 4, :o2, 29617207, 12
-
1
tz.transition 2045, 9, :o1, 29618971, 12
-
1
tz.transition 2046, 4, :o2, 29621575, 12
-
1
tz.transition 2046, 9, :o1, 29623423, 12
-
1
tz.transition 2047, 4, :o2, 29625943, 12
-
1
tz.transition 2047, 9, :o1, 29627791, 12
-
1
tz.transition 2048, 4, :o2, 29630311, 12
-
1
tz.transition 2048, 9, :o1, 29632159, 12
-
1
tz.transition 2049, 4, :o2, 29634679, 12
-
1
tz.transition 2049, 9, :o1, 29636527, 12
-
1
tz.transition 2050, 4, :o2, 29639047, 12
-
1
tz.transition 2050, 9, :o1, 29640895, 12
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Africa
-
1
module Harare
-
1
include TimezoneDefinition
-
-
1
timezone 'Africa/Harare' do |tz|
-
1
tz.offset :o0, 7452, 0, :LMT
-
1
tz.offset :o1, 7200, 0, :CAT
-
-
1
tz.transition 1903, 2, :o1, 1932939531, 800
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Africa
-
1
module Johannesburg
-
1
include TimezoneDefinition
-
-
1
timezone 'Africa/Johannesburg' do |tz|
-
1
tz.offset :o0, 6720, 0, :LMT
-
1
tz.offset :o1, 5400, 0, :SAST
-
1
tz.offset :o2, 7200, 0, :SAST
-
1
tz.offset :o3, 7200, 3600, :SAST
-
-
1
tz.transition 1892, 2, :o1, 108546139, 45
-
1
tz.transition 1903, 2, :o2, 38658791, 16
-
1
tz.transition 1942, 9, :o3, 4861245, 2
-
1
tz.transition 1943, 3, :o2, 58339307, 24
-
1
tz.transition 1943, 9, :o3, 4861973, 2
-
1
tz.transition 1944, 3, :o2, 58348043, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Africa
-
1
module Monrovia
-
1
include TimezoneDefinition
-
-
1
timezone 'Africa/Monrovia' do |tz|
-
1
tz.offset :o0, -2588, 0, :LMT
-
1
tz.offset :o1, -2588, 0, :MMT
-
1
tz.offset :o2, -2670, 0, :LRT
-
1
tz.offset :o3, 0, 0, :GMT
-
-
1
tz.transition 1882, 1, :o1, 52022445047, 21600
-
1
tz.transition 1919, 3, :o2, 52315600247, 21600
-
1
tz.transition 1972, 5, :o3, 73529070
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Africa
-
1
module Nairobi
-
1
include TimezoneDefinition
-
-
1
timezone 'Africa/Nairobi' do |tz|
-
1
tz.offset :o0, 8836, 0, :LMT
-
1
tz.offset :o1, 10800, 0, :EAT
-
1
tz.offset :o2, 9000, 0, :BEAT
-
1
tz.offset :o3, 9900, 0, :BEAUT
-
-
1
tz.transition 1928, 6, :o1, 52389253391, 21600
-
1
tz.transition 1929, 12, :o2, 19407819, 8
-
1
tz.transition 1939, 12, :o3, 116622211, 48
-
1
tz.transition 1959, 12, :o1, 233945701, 96
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Argentina
-
1
module Buenos_Aires
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Argentina/Buenos_Aires' do |tz|
-
1
tz.offset :o0, -14028, 0, :LMT
-
1
tz.offset :o1, -15408, 0, :CMT
-
1
tz.offset :o2, -14400, 0, :ART
-
1
tz.offset :o3, -14400, 3600, :ARST
-
1
tz.offset :o4, -10800, 0, :ART
-
1
tz.offset :o5, -10800, 3600, :ARST
-
-
1
tz.transition 1894, 10, :o1, 17374555169, 7200
-
1
tz.transition 1920, 5, :o2, 1453467407, 600
-
1
tz.transition 1930, 12, :o3, 7278935, 3
-
1
tz.transition 1931, 4, :o2, 19411461, 8
-
1
tz.transition 1931, 10, :o3, 7279889, 3
-
1
tz.transition 1932, 3, :o2, 19414141, 8
-
1
tz.transition 1932, 11, :o3, 7281038, 3
-
1
tz.transition 1933, 3, :o2, 19417061, 8
-
1
tz.transition 1933, 11, :o3, 7282133, 3
-
1
tz.transition 1934, 3, :o2, 19419981, 8
-
1
tz.transition 1934, 11, :o3, 7283228, 3
-
1
tz.transition 1935, 3, :o2, 19422901, 8
-
1
tz.transition 1935, 11, :o3, 7284323, 3
-
1
tz.transition 1936, 3, :o2, 19425829, 8
-
1
tz.transition 1936, 11, :o3, 7285421, 3
-
1
tz.transition 1937, 3, :o2, 19428749, 8
-
1
tz.transition 1937, 11, :o3, 7286516, 3
-
1
tz.transition 1938, 3, :o2, 19431669, 8
-
1
tz.transition 1938, 11, :o3, 7287611, 3
-
1
tz.transition 1939, 3, :o2, 19434589, 8
-
1
tz.transition 1939, 11, :o3, 7288706, 3
-
1
tz.transition 1940, 3, :o2, 19437517, 8
-
1
tz.transition 1940, 7, :o3, 7289435, 3
-
1
tz.transition 1941, 6, :o2, 19441285, 8
-
1
tz.transition 1941, 10, :o3, 7290848, 3
-
1
tz.transition 1943, 8, :o2, 19447501, 8
-
1
tz.transition 1943, 10, :o3, 7293038, 3
-
1
tz.transition 1946, 3, :o2, 19455045, 8
-
1
tz.transition 1946, 10, :o3, 7296284, 3
-
1
tz.transition 1963, 10, :o2, 19506429, 8
-
1
tz.transition 1963, 12, :o3, 7315136, 3
-
1
tz.transition 1964, 3, :o2, 19507645, 8
-
1
tz.transition 1964, 10, :o3, 7316051, 3
-
1
tz.transition 1965, 3, :o2, 19510565, 8
-
1
tz.transition 1965, 10, :o3, 7317146, 3
-
1
tz.transition 1966, 3, :o2, 19513485, 8
-
1
tz.transition 1966, 10, :o3, 7318241, 3
-
1
tz.transition 1967, 4, :o2, 19516661, 8
-
1
tz.transition 1967, 10, :o3, 7319294, 3
-
1
tz.transition 1968, 4, :o2, 19519629, 8
-
1
tz.transition 1968, 10, :o3, 7320407, 3
-
1
tz.transition 1969, 4, :o2, 19522541, 8
-
1
tz.transition 1969, 10, :o4, 7321499, 3
-
1
tz.transition 1974, 1, :o5, 128142000
-
1
tz.transition 1974, 5, :o4, 136605600
-
1
tz.transition 1988, 12, :o5, 596948400
-
1
tz.transition 1989, 3, :o4, 605066400
-
1
tz.transition 1989, 10, :o5, 624423600
-
1
tz.transition 1990, 3, :o4, 636516000
-
1
tz.transition 1990, 10, :o5, 656478000
-
1
tz.transition 1991, 3, :o4, 667965600
-
1
tz.transition 1991, 10, :o5, 687927600
-
1
tz.transition 1992, 3, :o4, 699415200
-
1
tz.transition 1992, 10, :o5, 719377200
-
1
tz.transition 1993, 3, :o4, 731469600
-
1
tz.transition 1999, 10, :o3, 938919600
-
1
tz.transition 2000, 3, :o4, 952052400
-
1
tz.transition 2007, 12, :o5, 1198983600
-
1
tz.transition 2008, 3, :o4, 1205632800
-
1
tz.transition 2008, 10, :o5, 1224385200
-
1
tz.transition 2009, 3, :o4, 1237082400
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Bogota
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Bogota' do |tz|
-
1
tz.offset :o0, -17780, 0, :LMT
-
1
tz.offset :o1, -17780, 0, :BMT
-
1
tz.offset :o2, -18000, 0, :COT
-
1
tz.offset :o3, -18000, 3600, :COST
-
-
1
tz.transition 1884, 3, :o1, 10407954409, 4320
-
1
tz.transition 1914, 11, :o2, 10456385929, 4320
-
1
tz.transition 1992, 5, :o3, 704869200
-
1
tz.transition 1993, 4, :o2, 733896000
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Caracas
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Caracas' do |tz|
-
1
tz.offset :o0, -16064, 0, :LMT
-
1
tz.offset :o1, -16060, 0, :CMT
-
1
tz.offset :o2, -16200, 0, :VET
-
1
tz.offset :o3, -14400, 0, :VET
-
-
1
tz.transition 1890, 1, :o1, 1627673863, 675
-
1
tz.transition 1912, 2, :o2, 10452001043, 4320
-
1
tz.transition 1965, 1, :o3, 39020187, 16
-
1
tz.transition 2007, 12, :o2, 1197183600
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Chicago
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Chicago' do |tz|
-
1
tz.offset :o0, -21036, 0, :LMT
-
1
tz.offset :o1, -21600, 0, :CST
-
1
tz.offset :o2, -21600, 3600, :CDT
-
1
tz.offset :o3, -18000, 0, :EST
-
1
tz.offset :o4, -21600, 3600, :CWT
-
1
tz.offset :o5, -21600, 3600, :CPT
-
-
1
tz.transition 1883, 11, :o1, 9636533, 4
-
1
tz.transition 1918, 3, :o2, 14530103, 6
-
1
tz.transition 1918, 10, :o1, 58125451, 24
-
1
tz.transition 1919, 3, :o2, 14532287, 6
-
1
tz.transition 1919, 10, :o1, 58134187, 24
-
1
tz.transition 1920, 6, :o2, 14534933, 6
-
1
tz.transition 1920, 10, :o1, 58143091, 24
-
1
tz.transition 1921, 3, :o2, 14536655, 6
-
1
tz.transition 1921, 10, :o1, 58151827, 24
-
1
tz.transition 1922, 4, :o2, 14539049, 6
-
1
tz.transition 1922, 9, :o1, 58159723, 24
-
1
tz.transition 1923, 4, :o2, 14541233, 6
-
1
tz.transition 1923, 9, :o1, 58168627, 24
-
1
tz.transition 1924, 4, :o2, 14543417, 6
-
1
tz.transition 1924, 9, :o1, 58177363, 24
-
1
tz.transition 1925, 4, :o2, 14545601, 6
-
1
tz.transition 1925, 9, :o1, 58186099, 24
-
1
tz.transition 1926, 4, :o2, 14547785, 6
-
1
tz.transition 1926, 9, :o1, 58194835, 24
-
1
tz.transition 1927, 4, :o2, 14549969, 6
-
1
tz.transition 1927, 9, :o1, 58203571, 24
-
1
tz.transition 1928, 4, :o2, 14552195, 6
-
1
tz.transition 1928, 9, :o1, 58212475, 24
-
1
tz.transition 1929, 4, :o2, 14554379, 6
-
1
tz.transition 1929, 9, :o1, 58221211, 24
-
1
tz.transition 1930, 4, :o2, 14556563, 6
-
1
tz.transition 1930, 9, :o1, 58229947, 24
-
1
tz.transition 1931, 4, :o2, 14558747, 6
-
1
tz.transition 1931, 9, :o1, 58238683, 24
-
1
tz.transition 1932, 4, :o2, 14560931, 6
-
1
tz.transition 1932, 9, :o1, 58247419, 24
-
1
tz.transition 1933, 4, :o2, 14563157, 6
-
1
tz.transition 1933, 9, :o1, 58256155, 24
-
1
tz.transition 1934, 4, :o2, 14565341, 6
-
1
tz.transition 1934, 9, :o1, 58265059, 24
-
1
tz.transition 1935, 4, :o2, 14567525, 6
-
1
tz.transition 1935, 9, :o1, 58273795, 24
-
1
tz.transition 1936, 3, :o3, 14569373, 6
-
1
tz.transition 1936, 11, :o1, 58283707, 24
-
1
tz.transition 1937, 4, :o2, 14571893, 6
-
1
tz.transition 1937, 9, :o1, 58291267, 24
-
1
tz.transition 1938, 4, :o2, 14574077, 6
-
1
tz.transition 1938, 9, :o1, 58300003, 24
-
1
tz.transition 1939, 4, :o2, 14576303, 6
-
1
tz.transition 1939, 9, :o1, 58308739, 24
-
1
tz.transition 1940, 4, :o2, 14578487, 6
-
1
tz.transition 1940, 9, :o1, 58317643, 24
-
1
tz.transition 1941, 4, :o2, 14580671, 6
-
1
tz.transition 1941, 9, :o1, 58326379, 24
-
1
tz.transition 1942, 2, :o4, 14582399, 6
-
1
tz.transition 1945, 8, :o5, 58360379, 24
-
1
tz.transition 1945, 9, :o1, 58361491, 24
-
1
tz.transition 1946, 4, :o2, 14591633, 6
-
1
tz.transition 1946, 9, :o1, 58370227, 24
-
1
tz.transition 1947, 4, :o2, 14593817, 6
-
1
tz.transition 1947, 9, :o1, 58378963, 24
-
1
tz.transition 1948, 4, :o2, 14596001, 6
-
1
tz.transition 1948, 9, :o1, 58387699, 24
-
1
tz.transition 1949, 4, :o2, 14598185, 6
-
1
tz.transition 1949, 9, :o1, 58396435, 24
-
1
tz.transition 1950, 4, :o2, 14600411, 6
-
1
tz.transition 1950, 9, :o1, 58405171, 24
-
1
tz.transition 1951, 4, :o2, 14602595, 6
-
1
tz.transition 1951, 9, :o1, 58414075, 24
-
1
tz.transition 1952, 4, :o2, 14604779, 6
-
1
tz.transition 1952, 9, :o1, 58422811, 24
-
1
tz.transition 1953, 4, :o2, 14606963, 6
-
1
tz.transition 1953, 9, :o1, 58431547, 24
-
1
tz.transition 1954, 4, :o2, 14609147, 6
-
1
tz.transition 1954, 9, :o1, 58440283, 24
-
1
tz.transition 1955, 4, :o2, 14611331, 6
-
1
tz.transition 1955, 10, :o1, 58449859, 24
-
1
tz.transition 1956, 4, :o2, 14613557, 6
-
1
tz.transition 1956, 10, :o1, 58458595, 24
-
1
tz.transition 1957, 4, :o2, 14615741, 6
-
1
tz.transition 1957, 10, :o1, 58467331, 24
-
1
tz.transition 1958, 4, :o2, 14617925, 6
-
1
tz.transition 1958, 10, :o1, 58476067, 24
-
1
tz.transition 1959, 4, :o2, 14620109, 6
-
1
tz.transition 1959, 10, :o1, 58484803, 24
-
1
tz.transition 1960, 4, :o2, 14622293, 6
-
1
tz.transition 1960, 10, :o1, 58493707, 24
-
1
tz.transition 1961, 4, :o2, 14624519, 6
-
1
tz.transition 1961, 10, :o1, 58502443, 24
-
1
tz.transition 1962, 4, :o2, 14626703, 6
-
1
tz.transition 1962, 10, :o1, 58511179, 24
-
1
tz.transition 1963, 4, :o2, 14628887, 6
-
1
tz.transition 1963, 10, :o1, 58519915, 24
-
1
tz.transition 1964, 4, :o2, 14631071, 6
-
1
tz.transition 1964, 10, :o1, 58528651, 24
-
1
tz.transition 1965, 4, :o2, 14633255, 6
-
1
tz.transition 1965, 10, :o1, 58537555, 24
-
1
tz.transition 1966, 4, :o2, 14635439, 6
-
1
tz.transition 1966, 10, :o1, 58546291, 24
-
1
tz.transition 1967, 4, :o2, 14637665, 6
-
1
tz.transition 1967, 10, :o1, 58555027, 24
-
1
tz.transition 1968, 4, :o2, 14639849, 6
-
1
tz.transition 1968, 10, :o1, 58563763, 24
-
1
tz.transition 1969, 4, :o2, 14642033, 6
-
1
tz.transition 1969, 10, :o1, 58572499, 24
-
1
tz.transition 1970, 4, :o2, 9964800
-
1
tz.transition 1970, 10, :o1, 25686000
-
1
tz.transition 1971, 4, :o2, 41414400
-
1
tz.transition 1971, 10, :o1, 57740400
-
1
tz.transition 1972, 4, :o2, 73468800
-
1
tz.transition 1972, 10, :o1, 89190000
-
1
tz.transition 1973, 4, :o2, 104918400
-
1
tz.transition 1973, 10, :o1, 120639600
-
1
tz.transition 1974, 1, :o2, 126691200
-
1
tz.transition 1974, 10, :o1, 152089200
-
1
tz.transition 1975, 2, :o2, 162374400
-
1
tz.transition 1975, 10, :o1, 183538800
-
1
tz.transition 1976, 4, :o2, 199267200
-
1
tz.transition 1976, 10, :o1, 215593200
-
1
tz.transition 1977, 4, :o2, 230716800
-
1
tz.transition 1977, 10, :o1, 247042800
-
1
tz.transition 1978, 4, :o2, 262771200
-
1
tz.transition 1978, 10, :o1, 278492400
-
1
tz.transition 1979, 4, :o2, 294220800
-
1
tz.transition 1979, 10, :o1, 309942000
-
1
tz.transition 1980, 4, :o2, 325670400
-
1
tz.transition 1980, 10, :o1, 341391600
-
1
tz.transition 1981, 4, :o2, 357120000
-
1
tz.transition 1981, 10, :o1, 372841200
-
1
tz.transition 1982, 4, :o2, 388569600
-
1
tz.transition 1982, 10, :o1, 404895600
-
1
tz.transition 1983, 4, :o2, 420019200
-
1
tz.transition 1983, 10, :o1, 436345200
-
1
tz.transition 1984, 4, :o2, 452073600
-
1
tz.transition 1984, 10, :o1, 467794800
-
1
tz.transition 1985, 4, :o2, 483523200
-
1
tz.transition 1985, 10, :o1, 499244400
-
1
tz.transition 1986, 4, :o2, 514972800
-
1
tz.transition 1986, 10, :o1, 530694000
-
1
tz.transition 1987, 4, :o2, 544608000
-
1
tz.transition 1987, 10, :o1, 562143600
-
1
tz.transition 1988, 4, :o2, 576057600
-
1
tz.transition 1988, 10, :o1, 594198000
-
1
tz.transition 1989, 4, :o2, 607507200
-
1
tz.transition 1989, 10, :o1, 625647600
-
1
tz.transition 1990, 4, :o2, 638956800
-
1
tz.transition 1990, 10, :o1, 657097200
-
1
tz.transition 1991, 4, :o2, 671011200
-
1
tz.transition 1991, 10, :o1, 688546800
-
1
tz.transition 1992, 4, :o2, 702460800
-
1
tz.transition 1992, 10, :o1, 719996400
-
1
tz.transition 1993, 4, :o2, 733910400
-
1
tz.transition 1993, 10, :o1, 752050800
-
1
tz.transition 1994, 4, :o2, 765360000
-
1
tz.transition 1994, 10, :o1, 783500400
-
1
tz.transition 1995, 4, :o2, 796809600
-
1
tz.transition 1995, 10, :o1, 814950000
-
1
tz.transition 1996, 4, :o2, 828864000
-
1
tz.transition 1996, 10, :o1, 846399600
-
1
tz.transition 1997, 4, :o2, 860313600
-
1
tz.transition 1997, 10, :o1, 877849200
-
1
tz.transition 1998, 4, :o2, 891763200
-
1
tz.transition 1998, 10, :o1, 909298800
-
1
tz.transition 1999, 4, :o2, 923212800
-
1
tz.transition 1999, 10, :o1, 941353200
-
1
tz.transition 2000, 4, :o2, 954662400
-
1
tz.transition 2000, 10, :o1, 972802800
-
1
tz.transition 2001, 4, :o2, 986112000
-
1
tz.transition 2001, 10, :o1, 1004252400
-
1
tz.transition 2002, 4, :o2, 1018166400
-
1
tz.transition 2002, 10, :o1, 1035702000
-
1
tz.transition 2003, 4, :o2, 1049616000
-
1
tz.transition 2003, 10, :o1, 1067151600
-
1
tz.transition 2004, 4, :o2, 1081065600
-
1
tz.transition 2004, 10, :o1, 1099206000
-
1
tz.transition 2005, 4, :o2, 1112515200
-
1
tz.transition 2005, 10, :o1, 1130655600
-
1
tz.transition 2006, 4, :o2, 1143964800
-
1
tz.transition 2006, 10, :o1, 1162105200
-
1
tz.transition 2007, 3, :o2, 1173600000
-
1
tz.transition 2007, 11, :o1, 1194159600
-
1
tz.transition 2008, 3, :o2, 1205049600
-
1
tz.transition 2008, 11, :o1, 1225609200
-
1
tz.transition 2009, 3, :o2, 1236499200
-
1
tz.transition 2009, 11, :o1, 1257058800
-
1
tz.transition 2010, 3, :o2, 1268553600
-
1
tz.transition 2010, 11, :o1, 1289113200
-
1
tz.transition 2011, 3, :o2, 1300003200
-
1
tz.transition 2011, 11, :o1, 1320562800
-
1
tz.transition 2012, 3, :o2, 1331452800
-
1
tz.transition 2012, 11, :o1, 1352012400
-
1
tz.transition 2013, 3, :o2, 1362902400
-
1
tz.transition 2013, 11, :o1, 1383462000
-
1
tz.transition 2014, 3, :o2, 1394352000
-
1
tz.transition 2014, 11, :o1, 1414911600
-
1
tz.transition 2015, 3, :o2, 1425801600
-
1
tz.transition 2015, 11, :o1, 1446361200
-
1
tz.transition 2016, 3, :o2, 1457856000
-
1
tz.transition 2016, 11, :o1, 1478415600
-
1
tz.transition 2017, 3, :o2, 1489305600
-
1
tz.transition 2017, 11, :o1, 1509865200
-
1
tz.transition 2018, 3, :o2, 1520755200
-
1
tz.transition 2018, 11, :o1, 1541314800
-
1
tz.transition 2019, 3, :o2, 1552204800
-
1
tz.transition 2019, 11, :o1, 1572764400
-
1
tz.transition 2020, 3, :o2, 1583654400
-
1
tz.transition 2020, 11, :o1, 1604214000
-
1
tz.transition 2021, 3, :o2, 1615708800
-
1
tz.transition 2021, 11, :o1, 1636268400
-
1
tz.transition 2022, 3, :o2, 1647158400
-
1
tz.transition 2022, 11, :o1, 1667718000
-
1
tz.transition 2023, 3, :o2, 1678608000
-
1
tz.transition 2023, 11, :o1, 1699167600
-
1
tz.transition 2024, 3, :o2, 1710057600
-
1
tz.transition 2024, 11, :o1, 1730617200
-
1
tz.transition 2025, 3, :o2, 1741507200
-
1
tz.transition 2025, 11, :o1, 1762066800
-
1
tz.transition 2026, 3, :o2, 1772956800
-
1
tz.transition 2026, 11, :o1, 1793516400
-
1
tz.transition 2027, 3, :o2, 1805011200
-
1
tz.transition 2027, 11, :o1, 1825570800
-
1
tz.transition 2028, 3, :o2, 1836460800
-
1
tz.transition 2028, 11, :o1, 1857020400
-
1
tz.transition 2029, 3, :o2, 1867910400
-
1
tz.transition 2029, 11, :o1, 1888470000
-
1
tz.transition 2030, 3, :o2, 1899360000
-
1
tz.transition 2030, 11, :o1, 1919919600
-
1
tz.transition 2031, 3, :o2, 1930809600
-
1
tz.transition 2031, 11, :o1, 1951369200
-
1
tz.transition 2032, 3, :o2, 1962864000
-
1
tz.transition 2032, 11, :o1, 1983423600
-
1
tz.transition 2033, 3, :o2, 1994313600
-
1
tz.transition 2033, 11, :o1, 2014873200
-
1
tz.transition 2034, 3, :o2, 2025763200
-
1
tz.transition 2034, 11, :o1, 2046322800
-
1
tz.transition 2035, 3, :o2, 2057212800
-
1
tz.transition 2035, 11, :o1, 2077772400
-
1
tz.transition 2036, 3, :o2, 2088662400
-
1
tz.transition 2036, 11, :o1, 2109222000
-
1
tz.transition 2037, 3, :o2, 2120112000
-
1
tz.transition 2037, 11, :o1, 2140671600
-
1
tz.transition 2038, 3, :o2, 14792981, 6
-
1
tz.transition 2038, 11, :o1, 59177635, 24
-
1
tz.transition 2039, 3, :o2, 14795165, 6
-
1
tz.transition 2039, 11, :o1, 59186371, 24
-
1
tz.transition 2040, 3, :o2, 14797349, 6
-
1
tz.transition 2040, 11, :o1, 59195107, 24
-
1
tz.transition 2041, 3, :o2, 14799533, 6
-
1
tz.transition 2041, 11, :o1, 59203843, 24
-
1
tz.transition 2042, 3, :o2, 14801717, 6
-
1
tz.transition 2042, 11, :o1, 59212579, 24
-
1
tz.transition 2043, 3, :o2, 14803901, 6
-
1
tz.transition 2043, 11, :o1, 59221315, 24
-
1
tz.transition 2044, 3, :o2, 14806127, 6
-
1
tz.transition 2044, 11, :o1, 59230219, 24
-
1
tz.transition 2045, 3, :o2, 14808311, 6
-
1
tz.transition 2045, 11, :o1, 59238955, 24
-
1
tz.transition 2046, 3, :o2, 14810495, 6
-
1
tz.transition 2046, 11, :o1, 59247691, 24
-
1
tz.transition 2047, 3, :o2, 14812679, 6
-
1
tz.transition 2047, 11, :o1, 59256427, 24
-
1
tz.transition 2048, 3, :o2, 14814863, 6
-
1
tz.transition 2048, 11, :o1, 59265163, 24
-
1
tz.transition 2049, 3, :o2, 14817089, 6
-
1
tz.transition 2049, 11, :o1, 59274067, 24
-
1
tz.transition 2050, 3, :o2, 14819273, 6
-
1
tz.transition 2050, 11, :o1, 59282803, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Chihuahua
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Chihuahua' do |tz|
-
1
tz.offset :o0, -25460, 0, :LMT
-
1
tz.offset :o1, -25200, 0, :MST
-
1
tz.offset :o2, -21600, 0, :CST
-
1
tz.offset :o3, -21600, 3600, :CDT
-
1
tz.offset :o4, -25200, 3600, :MDT
-
-
1
tz.transition 1922, 1, :o1, 58153339, 24
-
1
tz.transition 1927, 6, :o2, 9700171, 4
-
1
tz.transition 1930, 11, :o1, 9705183, 4
-
1
tz.transition 1931, 5, :o2, 9705855, 4
-
1
tz.transition 1931, 10, :o1, 9706463, 4
-
1
tz.transition 1932, 4, :o2, 58243171, 24
-
1
tz.transition 1996, 4, :o3, 828864000
-
1
tz.transition 1996, 10, :o2, 846399600
-
1
tz.transition 1997, 4, :o3, 860313600
-
1
tz.transition 1997, 10, :o2, 877849200
-
1
tz.transition 1998, 4, :o4, 891766800
-
1
tz.transition 1998, 10, :o1, 909302400
-
1
tz.transition 1999, 4, :o4, 923216400
-
1
tz.transition 1999, 10, :o1, 941356800
-
1
tz.transition 2000, 4, :o4, 954666000
-
1
tz.transition 2000, 10, :o1, 972806400
-
1
tz.transition 2001, 5, :o4, 989139600
-
1
tz.transition 2001, 9, :o1, 1001836800
-
1
tz.transition 2002, 4, :o4, 1018170000
-
1
tz.transition 2002, 10, :o1, 1035705600
-
1
tz.transition 2003, 4, :o4, 1049619600
-
1
tz.transition 2003, 10, :o1, 1067155200
-
1
tz.transition 2004, 4, :o4, 1081069200
-
1
tz.transition 2004, 10, :o1, 1099209600
-
1
tz.transition 2005, 4, :o4, 1112518800
-
1
tz.transition 2005, 10, :o1, 1130659200
-
1
tz.transition 2006, 4, :o4, 1143968400
-
1
tz.transition 2006, 10, :o1, 1162108800
-
1
tz.transition 2007, 4, :o4, 1175418000
-
1
tz.transition 2007, 10, :o1, 1193558400
-
1
tz.transition 2008, 4, :o4, 1207472400
-
1
tz.transition 2008, 10, :o1, 1225008000
-
1
tz.transition 2009, 4, :o4, 1238922000
-
1
tz.transition 2009, 10, :o1, 1256457600
-
1
tz.transition 2010, 4, :o4, 1270371600
-
1
tz.transition 2010, 10, :o1, 1288512000
-
1
tz.transition 2011, 4, :o4, 1301821200
-
1
tz.transition 2011, 10, :o1, 1319961600
-
1
tz.transition 2012, 4, :o4, 1333270800
-
1
tz.transition 2012, 10, :o1, 1351411200
-
1
tz.transition 2013, 4, :o4, 1365325200
-
1
tz.transition 2013, 10, :o1, 1382860800
-
1
tz.transition 2014, 4, :o4, 1396774800
-
1
tz.transition 2014, 10, :o1, 1414310400
-
1
tz.transition 2015, 4, :o4, 1428224400
-
1
tz.transition 2015, 10, :o1, 1445760000
-
1
tz.transition 2016, 4, :o4, 1459674000
-
1
tz.transition 2016, 10, :o1, 1477814400
-
1
tz.transition 2017, 4, :o4, 1491123600
-
1
tz.transition 2017, 10, :o1, 1509264000
-
1
tz.transition 2018, 4, :o4, 1522573200
-
1
tz.transition 2018, 10, :o1, 1540713600
-
1
tz.transition 2019, 4, :o4, 1554627600
-
1
tz.transition 2019, 10, :o1, 1572163200
-
1
tz.transition 2020, 4, :o4, 1586077200
-
1
tz.transition 2020, 10, :o1, 1603612800
-
1
tz.transition 2021, 4, :o4, 1617526800
-
1
tz.transition 2021, 10, :o1, 1635667200
-
1
tz.transition 2022, 4, :o4, 1648976400
-
1
tz.transition 2022, 10, :o1, 1667116800
-
1
tz.transition 2023, 4, :o4, 1680426000
-
1
tz.transition 2023, 10, :o1, 1698566400
-
1
tz.transition 2024, 4, :o4, 1712480400
-
1
tz.transition 2024, 10, :o1, 1730016000
-
1
tz.transition 2025, 4, :o4, 1743930000
-
1
tz.transition 2025, 10, :o1, 1761465600
-
1
tz.transition 2026, 4, :o4, 1775379600
-
1
tz.transition 2026, 10, :o1, 1792915200
-
1
tz.transition 2027, 4, :o4, 1806829200
-
1
tz.transition 2027, 10, :o1, 1824969600
-
1
tz.transition 2028, 4, :o4, 1838278800
-
1
tz.transition 2028, 10, :o1, 1856419200
-
1
tz.transition 2029, 4, :o4, 1869728400
-
1
tz.transition 2029, 10, :o1, 1887868800
-
1
tz.transition 2030, 4, :o4, 1901782800
-
1
tz.transition 2030, 10, :o1, 1919318400
-
1
tz.transition 2031, 4, :o4, 1933232400
-
1
tz.transition 2031, 10, :o1, 1950768000
-
1
tz.transition 2032, 4, :o4, 1964682000
-
1
tz.transition 2032, 10, :o1, 1982822400
-
1
tz.transition 2033, 4, :o4, 1996131600
-
1
tz.transition 2033, 10, :o1, 2014272000
-
1
tz.transition 2034, 4, :o4, 2027581200
-
1
tz.transition 2034, 10, :o1, 2045721600
-
1
tz.transition 2035, 4, :o4, 2059030800
-
1
tz.transition 2035, 10, :o1, 2077171200
-
1
tz.transition 2036, 4, :o4, 2091085200
-
1
tz.transition 2036, 10, :o1, 2108620800
-
1
tz.transition 2037, 4, :o4, 2122534800
-
1
tz.transition 2037, 10, :o1, 2140070400
-
1
tz.transition 2038, 4, :o4, 19724143, 8
-
1
tz.transition 2038, 10, :o1, 14794367, 6
-
1
tz.transition 2039, 4, :o4, 19727055, 8
-
1
tz.transition 2039, 10, :o1, 14796551, 6
-
1
tz.transition 2040, 4, :o4, 19729967, 8
-
1
tz.transition 2040, 10, :o1, 14798735, 6
-
1
tz.transition 2041, 4, :o4, 19732935, 8
-
1
tz.transition 2041, 10, :o1, 14800919, 6
-
1
tz.transition 2042, 4, :o4, 19735847, 8
-
1
tz.transition 2042, 10, :o1, 14803103, 6
-
1
tz.transition 2043, 4, :o4, 19738759, 8
-
1
tz.transition 2043, 10, :o1, 14805287, 6
-
1
tz.transition 2044, 4, :o4, 19741671, 8
-
1
tz.transition 2044, 10, :o1, 14807513, 6
-
1
tz.transition 2045, 4, :o4, 19744583, 8
-
1
tz.transition 2045, 10, :o1, 14809697, 6
-
1
tz.transition 2046, 4, :o4, 19747495, 8
-
1
tz.transition 2046, 10, :o1, 14811881, 6
-
1
tz.transition 2047, 4, :o4, 19750463, 8
-
1
tz.transition 2047, 10, :o1, 14814065, 6
-
1
tz.transition 2048, 4, :o4, 19753375, 8
-
1
tz.transition 2048, 10, :o1, 14816249, 6
-
1
tz.transition 2049, 4, :o4, 19756287, 8
-
1
tz.transition 2049, 10, :o1, 14818475, 6
-
1
tz.transition 2050, 4, :o4, 19759199, 8
-
1
tz.transition 2050, 10, :o1, 14820659, 6
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Denver
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Denver' do |tz|
-
1
tz.offset :o0, -25196, 0, :LMT
-
1
tz.offset :o1, -25200, 0, :MST
-
1
tz.offset :o2, -25200, 3600, :MDT
-
1
tz.offset :o3, -25200, 3600, :MWT
-
1
tz.offset :o4, -25200, 3600, :MPT
-
-
1
tz.transition 1883, 11, :o1, 57819199, 24
-
1
tz.transition 1918, 3, :o2, 19373471, 8
-
1
tz.transition 1918, 10, :o1, 14531363, 6
-
1
tz.transition 1919, 3, :o2, 19376383, 8
-
1
tz.transition 1919, 10, :o1, 14533547, 6
-
1
tz.transition 1920, 3, :o2, 19379295, 8
-
1
tz.transition 1920, 10, :o1, 14535773, 6
-
1
tz.transition 1921, 3, :o2, 19382207, 8
-
1
tz.transition 1921, 5, :o1, 14536991, 6
-
1
tz.transition 1942, 2, :o3, 19443199, 8
-
1
tz.transition 1945, 8, :o4, 58360379, 24
-
1
tz.transition 1945, 9, :o1, 14590373, 6
-
1
tz.transition 1965, 4, :o2, 19511007, 8
-
1
tz.transition 1965, 10, :o1, 14634389, 6
-
1
tz.transition 1966, 4, :o2, 19513919, 8
-
1
tz.transition 1966, 10, :o1, 14636573, 6
-
1
tz.transition 1967, 4, :o2, 19516887, 8
-
1
tz.transition 1967, 10, :o1, 14638757, 6
-
1
tz.transition 1968, 4, :o2, 19519799, 8
-
1
tz.transition 1968, 10, :o1, 14640941, 6
-
1
tz.transition 1969, 4, :o2, 19522711, 8
-
1
tz.transition 1969, 10, :o1, 14643125, 6
-
1
tz.transition 1970, 4, :o2, 9968400
-
1
tz.transition 1970, 10, :o1, 25689600
-
1
tz.transition 1971, 4, :o2, 41418000
-
1
tz.transition 1971, 10, :o1, 57744000
-
1
tz.transition 1972, 4, :o2, 73472400
-
1
tz.transition 1972, 10, :o1, 89193600
-
1
tz.transition 1973, 4, :o2, 104922000
-
1
tz.transition 1973, 10, :o1, 120643200
-
1
tz.transition 1974, 1, :o2, 126694800
-
1
tz.transition 1974, 10, :o1, 152092800
-
1
tz.transition 1975, 2, :o2, 162378000
-
1
tz.transition 1975, 10, :o1, 183542400
-
1
tz.transition 1976, 4, :o2, 199270800
-
1
tz.transition 1976, 10, :o1, 215596800
-
1
tz.transition 1977, 4, :o2, 230720400
-
1
tz.transition 1977, 10, :o1, 247046400
-
1
tz.transition 1978, 4, :o2, 262774800
-
1
tz.transition 1978, 10, :o1, 278496000
-
1
tz.transition 1979, 4, :o2, 294224400
-
1
tz.transition 1979, 10, :o1, 309945600
-
1
tz.transition 1980, 4, :o2, 325674000
-
1
tz.transition 1980, 10, :o1, 341395200
-
1
tz.transition 1981, 4, :o2, 357123600
-
1
tz.transition 1981, 10, :o1, 372844800
-
1
tz.transition 1982, 4, :o2, 388573200
-
1
tz.transition 1982, 10, :o1, 404899200
-
1
tz.transition 1983, 4, :o2, 420022800
-
1
tz.transition 1983, 10, :o1, 436348800
-
1
tz.transition 1984, 4, :o2, 452077200
-
1
tz.transition 1984, 10, :o1, 467798400
-
1
tz.transition 1985, 4, :o2, 483526800
-
1
tz.transition 1985, 10, :o1, 499248000
-
1
tz.transition 1986, 4, :o2, 514976400
-
1
tz.transition 1986, 10, :o1, 530697600
-
1
tz.transition 1987, 4, :o2, 544611600
-
1
tz.transition 1987, 10, :o1, 562147200
-
1
tz.transition 1988, 4, :o2, 576061200
-
1
tz.transition 1988, 10, :o1, 594201600
-
1
tz.transition 1989, 4, :o2, 607510800
-
1
tz.transition 1989, 10, :o1, 625651200
-
1
tz.transition 1990, 4, :o2, 638960400
-
1
tz.transition 1990, 10, :o1, 657100800
-
1
tz.transition 1991, 4, :o2, 671014800
-
1
tz.transition 1991, 10, :o1, 688550400
-
1
tz.transition 1992, 4, :o2, 702464400
-
1
tz.transition 1992, 10, :o1, 720000000
-
1
tz.transition 1993, 4, :o2, 733914000
-
1
tz.transition 1993, 10, :o1, 752054400
-
1
tz.transition 1994, 4, :o2, 765363600
-
1
tz.transition 1994, 10, :o1, 783504000
-
1
tz.transition 1995, 4, :o2, 796813200
-
1
tz.transition 1995, 10, :o1, 814953600
-
1
tz.transition 1996, 4, :o2, 828867600
-
1
tz.transition 1996, 10, :o1, 846403200
-
1
tz.transition 1997, 4, :o2, 860317200
-
1
tz.transition 1997, 10, :o1, 877852800
-
1
tz.transition 1998, 4, :o2, 891766800
-
1
tz.transition 1998, 10, :o1, 909302400
-
1
tz.transition 1999, 4, :o2, 923216400
-
1
tz.transition 1999, 10, :o1, 941356800
-
1
tz.transition 2000, 4, :o2, 954666000
-
1
tz.transition 2000, 10, :o1, 972806400
-
1
tz.transition 2001, 4, :o2, 986115600
-
1
tz.transition 2001, 10, :o1, 1004256000
-
1
tz.transition 2002, 4, :o2, 1018170000
-
1
tz.transition 2002, 10, :o1, 1035705600
-
1
tz.transition 2003, 4, :o2, 1049619600
-
1
tz.transition 2003, 10, :o1, 1067155200
-
1
tz.transition 2004, 4, :o2, 1081069200
-
1
tz.transition 2004, 10, :o1, 1099209600
-
1
tz.transition 2005, 4, :o2, 1112518800
-
1
tz.transition 2005, 10, :o1, 1130659200
-
1
tz.transition 2006, 4, :o2, 1143968400
-
1
tz.transition 2006, 10, :o1, 1162108800
-
1
tz.transition 2007, 3, :o2, 1173603600
-
1
tz.transition 2007, 11, :o1, 1194163200
-
1
tz.transition 2008, 3, :o2, 1205053200
-
1
tz.transition 2008, 11, :o1, 1225612800
-
1
tz.transition 2009, 3, :o2, 1236502800
-
1
tz.transition 2009, 11, :o1, 1257062400
-
1
tz.transition 2010, 3, :o2, 1268557200
-
1
tz.transition 2010, 11, :o1, 1289116800
-
1
tz.transition 2011, 3, :o2, 1300006800
-
1
tz.transition 2011, 11, :o1, 1320566400
-
1
tz.transition 2012, 3, :o2, 1331456400
-
1
tz.transition 2012, 11, :o1, 1352016000
-
1
tz.transition 2013, 3, :o2, 1362906000
-
1
tz.transition 2013, 11, :o1, 1383465600
-
1
tz.transition 2014, 3, :o2, 1394355600
-
1
tz.transition 2014, 11, :o1, 1414915200
-
1
tz.transition 2015, 3, :o2, 1425805200
-
1
tz.transition 2015, 11, :o1, 1446364800
-
1
tz.transition 2016, 3, :o2, 1457859600
-
1
tz.transition 2016, 11, :o1, 1478419200
-
1
tz.transition 2017, 3, :o2, 1489309200
-
1
tz.transition 2017, 11, :o1, 1509868800
-
1
tz.transition 2018, 3, :o2, 1520758800
-
1
tz.transition 2018, 11, :o1, 1541318400
-
1
tz.transition 2019, 3, :o2, 1552208400
-
1
tz.transition 2019, 11, :o1, 1572768000
-
1
tz.transition 2020, 3, :o2, 1583658000
-
1
tz.transition 2020, 11, :o1, 1604217600
-
1
tz.transition 2021, 3, :o2, 1615712400
-
1
tz.transition 2021, 11, :o1, 1636272000
-
1
tz.transition 2022, 3, :o2, 1647162000
-
1
tz.transition 2022, 11, :o1, 1667721600
-
1
tz.transition 2023, 3, :o2, 1678611600
-
1
tz.transition 2023, 11, :o1, 1699171200
-
1
tz.transition 2024, 3, :o2, 1710061200
-
1
tz.transition 2024, 11, :o1, 1730620800
-
1
tz.transition 2025, 3, :o2, 1741510800
-
1
tz.transition 2025, 11, :o1, 1762070400
-
1
tz.transition 2026, 3, :o2, 1772960400
-
1
tz.transition 2026, 11, :o1, 1793520000
-
1
tz.transition 2027, 3, :o2, 1805014800
-
1
tz.transition 2027, 11, :o1, 1825574400
-
1
tz.transition 2028, 3, :o2, 1836464400
-
1
tz.transition 2028, 11, :o1, 1857024000
-
1
tz.transition 2029, 3, :o2, 1867914000
-
1
tz.transition 2029, 11, :o1, 1888473600
-
1
tz.transition 2030, 3, :o2, 1899363600
-
1
tz.transition 2030, 11, :o1, 1919923200
-
1
tz.transition 2031, 3, :o2, 1930813200
-
1
tz.transition 2031, 11, :o1, 1951372800
-
1
tz.transition 2032, 3, :o2, 1962867600
-
1
tz.transition 2032, 11, :o1, 1983427200
-
1
tz.transition 2033, 3, :o2, 1994317200
-
1
tz.transition 2033, 11, :o1, 2014876800
-
1
tz.transition 2034, 3, :o2, 2025766800
-
1
tz.transition 2034, 11, :o1, 2046326400
-
1
tz.transition 2035, 3, :o2, 2057216400
-
1
tz.transition 2035, 11, :o1, 2077776000
-
1
tz.transition 2036, 3, :o2, 2088666000
-
1
tz.transition 2036, 11, :o1, 2109225600
-
1
tz.transition 2037, 3, :o2, 2120115600
-
1
tz.transition 2037, 11, :o1, 2140675200
-
1
tz.transition 2038, 3, :o2, 19723975, 8
-
1
tz.transition 2038, 11, :o1, 14794409, 6
-
1
tz.transition 2039, 3, :o2, 19726887, 8
-
1
tz.transition 2039, 11, :o1, 14796593, 6
-
1
tz.transition 2040, 3, :o2, 19729799, 8
-
1
tz.transition 2040, 11, :o1, 14798777, 6
-
1
tz.transition 2041, 3, :o2, 19732711, 8
-
1
tz.transition 2041, 11, :o1, 14800961, 6
-
1
tz.transition 2042, 3, :o2, 19735623, 8
-
1
tz.transition 2042, 11, :o1, 14803145, 6
-
1
tz.transition 2043, 3, :o2, 19738535, 8
-
1
tz.transition 2043, 11, :o1, 14805329, 6
-
1
tz.transition 2044, 3, :o2, 19741503, 8
-
1
tz.transition 2044, 11, :o1, 14807555, 6
-
1
tz.transition 2045, 3, :o2, 19744415, 8
-
1
tz.transition 2045, 11, :o1, 14809739, 6
-
1
tz.transition 2046, 3, :o2, 19747327, 8
-
1
tz.transition 2046, 11, :o1, 14811923, 6
-
1
tz.transition 2047, 3, :o2, 19750239, 8
-
1
tz.transition 2047, 11, :o1, 14814107, 6
-
1
tz.transition 2048, 3, :o2, 19753151, 8
-
1
tz.transition 2048, 11, :o1, 14816291, 6
-
1
tz.transition 2049, 3, :o2, 19756119, 8
-
1
tz.transition 2049, 11, :o1, 14818517, 6
-
1
tz.transition 2050, 3, :o2, 19759031, 8
-
1
tz.transition 2050, 11, :o1, 14820701, 6
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Godthab
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Godthab' do |tz|
-
1
tz.offset :o0, -12416, 0, :LMT
-
1
tz.offset :o1, -10800, 0, :WGT
-
1
tz.offset :o2, -10800, 3600, :WGST
-
-
1
tz.transition 1916, 7, :o1, 3268448069, 1350
-
1
tz.transition 1980, 4, :o2, 323845200
-
1
tz.transition 1980, 9, :o1, 338950800
-
1
tz.transition 1981, 3, :o2, 354675600
-
1
tz.transition 1981, 9, :o1, 370400400
-
1
tz.transition 1982, 3, :o2, 386125200
-
1
tz.transition 1982, 9, :o1, 401850000
-
1
tz.transition 1983, 3, :o2, 417574800
-
1
tz.transition 1983, 9, :o1, 433299600
-
1
tz.transition 1984, 3, :o2, 449024400
-
1
tz.transition 1984, 9, :o1, 465354000
-
1
tz.transition 1985, 3, :o2, 481078800
-
1
tz.transition 1985, 9, :o1, 496803600
-
1
tz.transition 1986, 3, :o2, 512528400
-
1
tz.transition 1986, 9, :o1, 528253200
-
1
tz.transition 1987, 3, :o2, 543978000
-
1
tz.transition 1987, 9, :o1, 559702800
-
1
tz.transition 1988, 3, :o2, 575427600
-
1
tz.transition 1988, 9, :o1, 591152400
-
1
tz.transition 1989, 3, :o2, 606877200
-
1
tz.transition 1989, 9, :o1, 622602000
-
1
tz.transition 1990, 3, :o2, 638326800
-
1
tz.transition 1990, 9, :o1, 654656400
-
1
tz.transition 1991, 3, :o2, 670381200
-
1
tz.transition 1991, 9, :o1, 686106000
-
1
tz.transition 1992, 3, :o2, 701830800
-
1
tz.transition 1992, 9, :o1, 717555600
-
1
tz.transition 1993, 3, :o2, 733280400
-
1
tz.transition 1993, 9, :o1, 749005200
-
1
tz.transition 1994, 3, :o2, 764730000
-
1
tz.transition 1994, 9, :o1, 780454800
-
1
tz.transition 1995, 3, :o2, 796179600
-
1
tz.transition 1995, 9, :o1, 811904400
-
1
tz.transition 1996, 3, :o2, 828234000
-
1
tz.transition 1996, 10, :o1, 846378000
-
1
tz.transition 1997, 3, :o2, 859683600
-
1
tz.transition 1997, 10, :o1, 877827600
-
1
tz.transition 1998, 3, :o2, 891133200
-
1
tz.transition 1998, 10, :o1, 909277200
-
1
tz.transition 1999, 3, :o2, 922582800
-
1
tz.transition 1999, 10, :o1, 941331600
-
1
tz.transition 2000, 3, :o2, 954032400
-
1
tz.transition 2000, 10, :o1, 972781200
-
1
tz.transition 2001, 3, :o2, 985482000
-
1
tz.transition 2001, 10, :o1, 1004230800
-
1
tz.transition 2002, 3, :o2, 1017536400
-
1
tz.transition 2002, 10, :o1, 1035680400
-
1
tz.transition 2003, 3, :o2, 1048986000
-
1
tz.transition 2003, 10, :o1, 1067130000
-
1
tz.transition 2004, 3, :o2, 1080435600
-
1
tz.transition 2004, 10, :o1, 1099184400
-
1
tz.transition 2005, 3, :o2, 1111885200
-
1
tz.transition 2005, 10, :o1, 1130634000
-
1
tz.transition 2006, 3, :o2, 1143334800
-
1
tz.transition 2006, 10, :o1, 1162083600
-
1
tz.transition 2007, 3, :o2, 1174784400
-
1
tz.transition 2007, 10, :o1, 1193533200
-
1
tz.transition 2008, 3, :o2, 1206838800
-
1
tz.transition 2008, 10, :o1, 1224982800
-
1
tz.transition 2009, 3, :o2, 1238288400
-
1
tz.transition 2009, 10, :o1, 1256432400
-
1
tz.transition 2010, 3, :o2, 1269738000
-
1
tz.transition 2010, 10, :o1, 1288486800
-
1
tz.transition 2011, 3, :o2, 1301187600
-
1
tz.transition 2011, 10, :o1, 1319936400
-
1
tz.transition 2012, 3, :o2, 1332637200
-
1
tz.transition 2012, 10, :o1, 1351386000
-
1
tz.transition 2013, 3, :o2, 1364691600
-
1
tz.transition 2013, 10, :o1, 1382835600
-
1
tz.transition 2014, 3, :o2, 1396141200
-
1
tz.transition 2014, 10, :o1, 1414285200
-
1
tz.transition 2015, 3, :o2, 1427590800
-
1
tz.transition 2015, 10, :o1, 1445734800
-
1
tz.transition 2016, 3, :o2, 1459040400
-
1
tz.transition 2016, 10, :o1, 1477789200
-
1
tz.transition 2017, 3, :o2, 1490490000
-
1
tz.transition 2017, 10, :o1, 1509238800
-
1
tz.transition 2018, 3, :o2, 1521939600
-
1
tz.transition 2018, 10, :o1, 1540688400
-
1
tz.transition 2019, 3, :o2, 1553994000
-
1
tz.transition 2019, 10, :o1, 1572138000
-
1
tz.transition 2020, 3, :o2, 1585443600
-
1
tz.transition 2020, 10, :o1, 1603587600
-
1
tz.transition 2021, 3, :o2, 1616893200
-
1
tz.transition 2021, 10, :o1, 1635642000
-
1
tz.transition 2022, 3, :o2, 1648342800
-
1
tz.transition 2022, 10, :o1, 1667091600
-
1
tz.transition 2023, 3, :o2, 1679792400
-
1
tz.transition 2023, 10, :o1, 1698541200
-
1
tz.transition 2024, 3, :o2, 1711846800
-
1
tz.transition 2024, 10, :o1, 1729990800
-
1
tz.transition 2025, 3, :o2, 1743296400
-
1
tz.transition 2025, 10, :o1, 1761440400
-
1
tz.transition 2026, 3, :o2, 1774746000
-
1
tz.transition 2026, 10, :o1, 1792890000
-
1
tz.transition 2027, 3, :o2, 1806195600
-
1
tz.transition 2027, 10, :o1, 1824944400
-
1
tz.transition 2028, 3, :o2, 1837645200
-
1
tz.transition 2028, 10, :o1, 1856394000
-
1
tz.transition 2029, 3, :o2, 1869094800
-
1
tz.transition 2029, 10, :o1, 1887843600
-
1
tz.transition 2030, 3, :o2, 1901149200
-
1
tz.transition 2030, 10, :o1, 1919293200
-
1
tz.transition 2031, 3, :o2, 1932598800
-
1
tz.transition 2031, 10, :o1, 1950742800
-
1
tz.transition 2032, 3, :o2, 1964048400
-
1
tz.transition 2032, 10, :o1, 1982797200
-
1
tz.transition 2033, 3, :o2, 1995498000
-
1
tz.transition 2033, 10, :o1, 2014246800
-
1
tz.transition 2034, 3, :o2, 2026947600
-
1
tz.transition 2034, 10, :o1, 2045696400
-
1
tz.transition 2035, 3, :o2, 2058397200
-
1
tz.transition 2035, 10, :o1, 2077146000
-
1
tz.transition 2036, 3, :o2, 2090451600
-
1
tz.transition 2036, 10, :o1, 2108595600
-
1
tz.transition 2037, 3, :o2, 2121901200
-
1
tz.transition 2037, 10, :o1, 2140045200
-
1
tz.transition 2038, 3, :o2, 59172253, 24
-
1
tz.transition 2038, 10, :o1, 59177461, 24
-
1
tz.transition 2039, 3, :o2, 59180989, 24
-
1
tz.transition 2039, 10, :o1, 59186197, 24
-
1
tz.transition 2040, 3, :o2, 59189725, 24
-
1
tz.transition 2040, 10, :o1, 59194933, 24
-
1
tz.transition 2041, 3, :o2, 59198629, 24
-
1
tz.transition 2041, 10, :o1, 59203669, 24
-
1
tz.transition 2042, 3, :o2, 59207365, 24
-
1
tz.transition 2042, 10, :o1, 59212405, 24
-
1
tz.transition 2043, 3, :o2, 59216101, 24
-
1
tz.transition 2043, 10, :o1, 59221141, 24
-
1
tz.transition 2044, 3, :o2, 59224837, 24
-
1
tz.transition 2044, 10, :o1, 59230045, 24
-
1
tz.transition 2045, 3, :o2, 59233573, 24
-
1
tz.transition 2045, 10, :o1, 59238781, 24
-
1
tz.transition 2046, 3, :o2, 59242309, 24
-
1
tz.transition 2046, 10, :o1, 59247517, 24
-
1
tz.transition 2047, 3, :o2, 59251213, 24
-
1
tz.transition 2047, 10, :o1, 59256253, 24
-
1
tz.transition 2048, 3, :o2, 59259949, 24
-
1
tz.transition 2048, 10, :o1, 59264989, 24
-
1
tz.transition 2049, 3, :o2, 59268685, 24
-
1
tz.transition 2049, 10, :o1, 59273893, 24
-
1
tz.transition 2050, 3, :o2, 59277421, 24
-
1
tz.transition 2050, 10, :o1, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Guatemala
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Guatemala' do |tz|
-
1
tz.offset :o0, -21724, 0, :LMT
-
1
tz.offset :o1, -21600, 0, :CST
-
1
tz.offset :o2, -21600, 3600, :CDT
-
-
1
tz.transition 1918, 10, :o1, 52312429831, 21600
-
1
tz.transition 1973, 11, :o2, 123055200
-
1
tz.transition 1974, 2, :o1, 130914000
-
1
tz.transition 1983, 5, :o2, 422344800
-
1
tz.transition 1983, 9, :o1, 433054800
-
1
tz.transition 1991, 3, :o2, 669708000
-
1
tz.transition 1991, 9, :o1, 684219600
-
1
tz.transition 2006, 4, :o2, 1146376800
-
1
tz.transition 2006, 10, :o1, 1159678800
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Guyana
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Guyana' do |tz|
-
1
tz.offset :o0, -13960, 0, :LMT
-
1
tz.offset :o1, -13500, 0, :GBGT
-
1
tz.offset :o2, -13500, 0, :GYT
-
1
tz.offset :o3, -10800, 0, :GYT
-
1
tz.offset :o4, -14400, 0, :GYT
-
-
1
tz.transition 1915, 3, :o1, 5228404549, 2160
-
1
tz.transition 1966, 5, :o2, 78056693, 32
-
1
tz.transition 1975, 7, :o3, 176010300
-
1
tz.transition 1991, 1, :o4, 662698800
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Halifax
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Halifax' do |tz|
-
1
tz.offset :o0, -15264, 0, :LMT
-
1
tz.offset :o1, -14400, 0, :AST
-
1
tz.offset :o2, -14400, 3600, :ADT
-
1
tz.offset :o3, -14400, 3600, :AWT
-
1
tz.offset :o4, -14400, 3600, :APT
-
-
1
tz.transition 1902, 6, :o1, 724774703, 300
-
1
tz.transition 1916, 4, :o2, 7262864, 3
-
1
tz.transition 1916, 10, :o1, 19369101, 8
-
1
tz.transition 1918, 4, :o2, 9686791, 4
-
1
tz.transition 1918, 10, :o1, 58125449, 24
-
1
tz.transition 1920, 5, :o2, 7267361, 3
-
1
tz.transition 1920, 8, :o1, 19380525, 8
-
1
tz.transition 1921, 5, :o2, 7268447, 3
-
1
tz.transition 1921, 9, :o1, 19383501, 8
-
1
tz.transition 1922, 4, :o2, 7269524, 3
-
1
tz.transition 1922, 9, :o1, 19386421, 8
-
1
tz.transition 1923, 5, :o2, 7270637, 3
-
1
tz.transition 1923, 9, :o1, 19389333, 8
-
1
tz.transition 1924, 5, :o2, 7271729, 3
-
1
tz.transition 1924, 9, :o1, 19392349, 8
-
1
tz.transition 1925, 5, :o2, 7272821, 3
-
1
tz.transition 1925, 9, :o1, 19395373, 8
-
1
tz.transition 1926, 5, :o2, 7273955, 3
-
1
tz.transition 1926, 9, :o1, 19398173, 8
-
1
tz.transition 1927, 5, :o2, 7275005, 3
-
1
tz.transition 1927, 9, :o1, 19401197, 8
-
1
tz.transition 1928, 5, :o2, 7276139, 3
-
1
tz.transition 1928, 9, :o1, 19403989, 8
-
1
tz.transition 1929, 5, :o2, 7277231, 3
-
1
tz.transition 1929, 9, :o1, 19406861, 8
-
1
tz.transition 1930, 5, :o2, 7278323, 3
-
1
tz.transition 1930, 9, :o1, 19409877, 8
-
1
tz.transition 1931, 5, :o2, 7279415, 3
-
1
tz.transition 1931, 9, :o1, 19412901, 8
-
1
tz.transition 1932, 5, :o2, 7280486, 3
-
1
tz.transition 1932, 9, :o1, 19415813, 8
-
1
tz.transition 1933, 4, :o2, 7281578, 3
-
1
tz.transition 1933, 10, :o1, 19418781, 8
-
1
tz.transition 1934, 5, :o2, 7282733, 3
-
1
tz.transition 1934, 9, :o1, 19421573, 8
-
1
tz.transition 1935, 6, :o2, 7283867, 3
-
1
tz.transition 1935, 9, :o1, 19424605, 8
-
1
tz.transition 1936, 6, :o2, 7284962, 3
-
1
tz.transition 1936, 9, :o1, 19427405, 8
-
1
tz.transition 1937, 5, :o2, 7285967, 3
-
1
tz.transition 1937, 9, :o1, 19430429, 8
-
1
tz.transition 1938, 5, :o2, 7287059, 3
-
1
tz.transition 1938, 9, :o1, 19433341, 8
-
1
tz.transition 1939, 5, :o2, 7288235, 3
-
1
tz.transition 1939, 9, :o1, 19436253, 8
-
1
tz.transition 1940, 5, :o2, 7289264, 3
-
1
tz.transition 1940, 9, :o1, 19439221, 8
-
1
tz.transition 1941, 5, :o2, 7290356, 3
-
1
tz.transition 1941, 9, :o1, 19442133, 8
-
1
tz.transition 1942, 2, :o3, 9721599, 4
-
1
tz.transition 1945, 8, :o4, 58360379, 24
-
1
tz.transition 1945, 9, :o1, 58361489, 24
-
1
tz.transition 1946, 4, :o2, 9727755, 4
-
1
tz.transition 1946, 9, :o1, 58370225, 24
-
1
tz.transition 1947, 4, :o2, 9729211, 4
-
1
tz.transition 1947, 9, :o1, 58378961, 24
-
1
tz.transition 1948, 4, :o2, 9730667, 4
-
1
tz.transition 1948, 9, :o1, 58387697, 24
-
1
tz.transition 1949, 4, :o2, 9732123, 4
-
1
tz.transition 1949, 9, :o1, 58396433, 24
-
1
tz.transition 1951, 4, :o2, 9735063, 4
-
1
tz.transition 1951, 9, :o1, 58414073, 24
-
1
tz.transition 1952, 4, :o2, 9736519, 4
-
1
tz.transition 1952, 9, :o1, 58422809, 24
-
1
tz.transition 1953, 4, :o2, 9737975, 4
-
1
tz.transition 1953, 9, :o1, 58431545, 24
-
1
tz.transition 1954, 4, :o2, 9739431, 4
-
1
tz.transition 1954, 9, :o1, 58440281, 24
-
1
tz.transition 1956, 4, :o2, 9742371, 4
-
1
tz.transition 1956, 9, :o1, 58457921, 24
-
1
tz.transition 1957, 4, :o2, 9743827, 4
-
1
tz.transition 1957, 9, :o1, 58466657, 24
-
1
tz.transition 1958, 4, :o2, 9745283, 4
-
1
tz.transition 1958, 9, :o1, 58475393, 24
-
1
tz.transition 1959, 4, :o2, 9746739, 4
-
1
tz.transition 1959, 9, :o1, 58484129, 24
-
1
tz.transition 1962, 4, :o2, 9751135, 4
-
1
tz.transition 1962, 10, :o1, 58511177, 24
-
1
tz.transition 1963, 4, :o2, 9752591, 4
-
1
tz.transition 1963, 10, :o1, 58519913, 24
-
1
tz.transition 1964, 4, :o2, 9754047, 4
-
1
tz.transition 1964, 10, :o1, 58528649, 24
-
1
tz.transition 1965, 4, :o2, 9755503, 4
-
1
tz.transition 1965, 10, :o1, 58537553, 24
-
1
tz.transition 1966, 4, :o2, 9756959, 4
-
1
tz.transition 1966, 10, :o1, 58546289, 24
-
1
tz.transition 1967, 4, :o2, 9758443, 4
-
1
tz.transition 1967, 10, :o1, 58555025, 24
-
1
tz.transition 1968, 4, :o2, 9759899, 4
-
1
tz.transition 1968, 10, :o1, 58563761, 24
-
1
tz.transition 1969, 4, :o2, 9761355, 4
-
1
tz.transition 1969, 10, :o1, 58572497, 24
-
1
tz.transition 1970, 4, :o2, 9957600
-
1
tz.transition 1970, 10, :o1, 25678800
-
1
tz.transition 1971, 4, :o2, 41407200
-
1
tz.transition 1971, 10, :o1, 57733200
-
1
tz.transition 1972, 4, :o2, 73461600
-
1
tz.transition 1972, 10, :o1, 89182800
-
1
tz.transition 1973, 4, :o2, 104911200
-
1
tz.transition 1973, 10, :o1, 120632400
-
1
tz.transition 1974, 4, :o2, 136360800
-
1
tz.transition 1974, 10, :o1, 152082000
-
1
tz.transition 1975, 4, :o2, 167810400
-
1
tz.transition 1975, 10, :o1, 183531600
-
1
tz.transition 1976, 4, :o2, 199260000
-
1
tz.transition 1976, 10, :o1, 215586000
-
1
tz.transition 1977, 4, :o2, 230709600
-
1
tz.transition 1977, 10, :o1, 247035600
-
1
tz.transition 1978, 4, :o2, 262764000
-
1
tz.transition 1978, 10, :o1, 278485200
-
1
tz.transition 1979, 4, :o2, 294213600
-
1
tz.transition 1979, 10, :o1, 309934800
-
1
tz.transition 1980, 4, :o2, 325663200
-
1
tz.transition 1980, 10, :o1, 341384400
-
1
tz.transition 1981, 4, :o2, 357112800
-
1
tz.transition 1981, 10, :o1, 372834000
-
1
tz.transition 1982, 4, :o2, 388562400
-
1
tz.transition 1982, 10, :o1, 404888400
-
1
tz.transition 1983, 4, :o2, 420012000
-
1
tz.transition 1983, 10, :o1, 436338000
-
1
tz.transition 1984, 4, :o2, 452066400
-
1
tz.transition 1984, 10, :o1, 467787600
-
1
tz.transition 1985, 4, :o2, 483516000
-
1
tz.transition 1985, 10, :o1, 499237200
-
1
tz.transition 1986, 4, :o2, 514965600
-
1
tz.transition 1986, 10, :o1, 530686800
-
1
tz.transition 1987, 4, :o2, 544600800
-
1
tz.transition 1987, 10, :o1, 562136400
-
1
tz.transition 1988, 4, :o2, 576050400
-
1
tz.transition 1988, 10, :o1, 594190800
-
1
tz.transition 1989, 4, :o2, 607500000
-
1
tz.transition 1989, 10, :o1, 625640400
-
1
tz.transition 1990, 4, :o2, 638949600
-
1
tz.transition 1990, 10, :o1, 657090000
-
1
tz.transition 1991, 4, :o2, 671004000
-
1
tz.transition 1991, 10, :o1, 688539600
-
1
tz.transition 1992, 4, :o2, 702453600
-
1
tz.transition 1992, 10, :o1, 719989200
-
1
tz.transition 1993, 4, :o2, 733903200
-
1
tz.transition 1993, 10, :o1, 752043600
-
1
tz.transition 1994, 4, :o2, 765352800
-
1
tz.transition 1994, 10, :o1, 783493200
-
1
tz.transition 1995, 4, :o2, 796802400
-
1
tz.transition 1995, 10, :o1, 814942800
-
1
tz.transition 1996, 4, :o2, 828856800
-
1
tz.transition 1996, 10, :o1, 846392400
-
1
tz.transition 1997, 4, :o2, 860306400
-
1
tz.transition 1997, 10, :o1, 877842000
-
1
tz.transition 1998, 4, :o2, 891756000
-
1
tz.transition 1998, 10, :o1, 909291600
-
1
tz.transition 1999, 4, :o2, 923205600
-
1
tz.transition 1999, 10, :o1, 941346000
-
1
tz.transition 2000, 4, :o2, 954655200
-
1
tz.transition 2000, 10, :o1, 972795600
-
1
tz.transition 2001, 4, :o2, 986104800
-
1
tz.transition 2001, 10, :o1, 1004245200
-
1
tz.transition 2002, 4, :o2, 1018159200
-
1
tz.transition 2002, 10, :o1, 1035694800
-
1
tz.transition 2003, 4, :o2, 1049608800
-
1
tz.transition 2003, 10, :o1, 1067144400
-
1
tz.transition 2004, 4, :o2, 1081058400
-
1
tz.transition 2004, 10, :o1, 1099198800
-
1
tz.transition 2005, 4, :o2, 1112508000
-
1
tz.transition 2005, 10, :o1, 1130648400
-
1
tz.transition 2006, 4, :o2, 1143957600
-
1
tz.transition 2006, 10, :o1, 1162098000
-
1
tz.transition 2007, 3, :o2, 1173592800
-
1
tz.transition 2007, 11, :o1, 1194152400
-
1
tz.transition 2008, 3, :o2, 1205042400
-
1
tz.transition 2008, 11, :o1, 1225602000
-
1
tz.transition 2009, 3, :o2, 1236492000
-
1
tz.transition 2009, 11, :o1, 1257051600
-
1
tz.transition 2010, 3, :o2, 1268546400
-
1
tz.transition 2010, 11, :o1, 1289106000
-
1
tz.transition 2011, 3, :o2, 1299996000
-
1
tz.transition 2011, 11, :o1, 1320555600
-
1
tz.transition 2012, 3, :o2, 1331445600
-
1
tz.transition 2012, 11, :o1, 1352005200
-
1
tz.transition 2013, 3, :o2, 1362895200
-
1
tz.transition 2013, 11, :o1, 1383454800
-
1
tz.transition 2014, 3, :o2, 1394344800
-
1
tz.transition 2014, 11, :o1, 1414904400
-
1
tz.transition 2015, 3, :o2, 1425794400
-
1
tz.transition 2015, 11, :o1, 1446354000
-
1
tz.transition 2016, 3, :o2, 1457848800
-
1
tz.transition 2016, 11, :o1, 1478408400
-
1
tz.transition 2017, 3, :o2, 1489298400
-
1
tz.transition 2017, 11, :o1, 1509858000
-
1
tz.transition 2018, 3, :o2, 1520748000
-
1
tz.transition 2018, 11, :o1, 1541307600
-
1
tz.transition 2019, 3, :o2, 1552197600
-
1
tz.transition 2019, 11, :o1, 1572757200
-
1
tz.transition 2020, 3, :o2, 1583647200
-
1
tz.transition 2020, 11, :o1, 1604206800
-
1
tz.transition 2021, 3, :o2, 1615701600
-
1
tz.transition 2021, 11, :o1, 1636261200
-
1
tz.transition 2022, 3, :o2, 1647151200
-
1
tz.transition 2022, 11, :o1, 1667710800
-
1
tz.transition 2023, 3, :o2, 1678600800
-
1
tz.transition 2023, 11, :o1, 1699160400
-
1
tz.transition 2024, 3, :o2, 1710050400
-
1
tz.transition 2024, 11, :o1, 1730610000
-
1
tz.transition 2025, 3, :o2, 1741500000
-
1
tz.transition 2025, 11, :o1, 1762059600
-
1
tz.transition 2026, 3, :o2, 1772949600
-
1
tz.transition 2026, 11, :o1, 1793509200
-
1
tz.transition 2027, 3, :o2, 1805004000
-
1
tz.transition 2027, 11, :o1, 1825563600
-
1
tz.transition 2028, 3, :o2, 1836453600
-
1
tz.transition 2028, 11, :o1, 1857013200
-
1
tz.transition 2029, 3, :o2, 1867903200
-
1
tz.transition 2029, 11, :o1, 1888462800
-
1
tz.transition 2030, 3, :o2, 1899352800
-
1
tz.transition 2030, 11, :o1, 1919912400
-
1
tz.transition 2031, 3, :o2, 1930802400
-
1
tz.transition 2031, 11, :o1, 1951362000
-
1
tz.transition 2032, 3, :o2, 1962856800
-
1
tz.transition 2032, 11, :o1, 1983416400
-
1
tz.transition 2033, 3, :o2, 1994306400
-
1
tz.transition 2033, 11, :o1, 2014866000
-
1
tz.transition 2034, 3, :o2, 2025756000
-
1
tz.transition 2034, 11, :o1, 2046315600
-
1
tz.transition 2035, 3, :o2, 2057205600
-
1
tz.transition 2035, 11, :o1, 2077765200
-
1
tz.transition 2036, 3, :o2, 2088655200
-
1
tz.transition 2036, 11, :o1, 2109214800
-
1
tz.transition 2037, 3, :o2, 2120104800
-
1
tz.transition 2037, 11, :o1, 2140664400
-
1
tz.transition 2038, 3, :o2, 9861987, 4
-
1
tz.transition 2038, 11, :o1, 59177633, 24
-
1
tz.transition 2039, 3, :o2, 9863443, 4
-
1
tz.transition 2039, 11, :o1, 59186369, 24
-
1
tz.transition 2040, 3, :o2, 9864899, 4
-
1
tz.transition 2040, 11, :o1, 59195105, 24
-
1
tz.transition 2041, 3, :o2, 9866355, 4
-
1
tz.transition 2041, 11, :o1, 59203841, 24
-
1
tz.transition 2042, 3, :o2, 9867811, 4
-
1
tz.transition 2042, 11, :o1, 59212577, 24
-
1
tz.transition 2043, 3, :o2, 9869267, 4
-
1
tz.transition 2043, 11, :o1, 59221313, 24
-
1
tz.transition 2044, 3, :o2, 9870751, 4
-
1
tz.transition 2044, 11, :o1, 59230217, 24
-
1
tz.transition 2045, 3, :o2, 9872207, 4
-
1
tz.transition 2045, 11, :o1, 59238953, 24
-
1
tz.transition 2046, 3, :o2, 9873663, 4
-
1
tz.transition 2046, 11, :o1, 59247689, 24
-
1
tz.transition 2047, 3, :o2, 9875119, 4
-
1
tz.transition 2047, 11, :o1, 59256425, 24
-
1
tz.transition 2048, 3, :o2, 9876575, 4
-
1
tz.transition 2048, 11, :o1, 59265161, 24
-
1
tz.transition 2049, 3, :o2, 9878059, 4
-
1
tz.transition 2049, 11, :o1, 59274065, 24
-
1
tz.transition 2050, 3, :o2, 9879515, 4
-
1
tz.transition 2050, 11, :o1, 59282801, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Indiana
-
1
module Indianapolis
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Indiana/Indianapolis' do |tz|
-
1
tz.offset :o0, -20678, 0, :LMT
-
1
tz.offset :o1, -21600, 0, :CST
-
1
tz.offset :o2, -21600, 3600, :CDT
-
1
tz.offset :o3, -21600, 3600, :CWT
-
1
tz.offset :o4, -21600, 3600, :CPT
-
1
tz.offset :o5, -18000, 0, :EST
-
1
tz.offset :o6, -18000, 3600, :EDT
-
-
1
tz.transition 1883, 11, :o1, 9636533, 4
-
1
tz.transition 1918, 3, :o2, 14530103, 6
-
1
tz.transition 1918, 10, :o1, 58125451, 24
-
1
tz.transition 1919, 3, :o2, 14532287, 6
-
1
tz.transition 1919, 10, :o1, 58134187, 24
-
1
tz.transition 1941, 6, :o2, 14581007, 6
-
1
tz.transition 1941, 9, :o1, 58326379, 24
-
1
tz.transition 1942, 2, :o3, 14582399, 6
-
1
tz.transition 1945, 8, :o4, 58360379, 24
-
1
tz.transition 1945, 9, :o1, 58361491, 24
-
1
tz.transition 1946, 4, :o2, 14591633, 6
-
1
tz.transition 1946, 9, :o1, 58370227, 24
-
1
tz.transition 1947, 4, :o2, 14593817, 6
-
1
tz.transition 1947, 9, :o1, 58378963, 24
-
1
tz.transition 1948, 4, :o2, 14596001, 6
-
1
tz.transition 1948, 9, :o1, 58387699, 24
-
1
tz.transition 1949, 4, :o2, 14598185, 6
-
1
tz.transition 1949, 9, :o1, 58396435, 24
-
1
tz.transition 1950, 4, :o2, 14600411, 6
-
1
tz.transition 1950, 9, :o1, 58405171, 24
-
1
tz.transition 1951, 4, :o2, 14602595, 6
-
1
tz.transition 1951, 9, :o1, 58414075, 24
-
1
tz.transition 1952, 4, :o2, 14604779, 6
-
1
tz.transition 1952, 9, :o1, 58422811, 24
-
1
tz.transition 1953, 4, :o2, 14606963, 6
-
1
tz.transition 1953, 9, :o1, 58431547, 24
-
1
tz.transition 1954, 4, :o2, 14609147, 6
-
1
tz.transition 1954, 9, :o1, 58440283, 24
-
1
tz.transition 1955, 4, :o5, 14611331, 6
-
1
tz.transition 1957, 9, :o1, 58466659, 24
-
1
tz.transition 1958, 4, :o5, 14617925, 6
-
1
tz.transition 1969, 4, :o6, 58568131, 24
-
1
tz.transition 1969, 10, :o5, 9762083, 4
-
1
tz.transition 1970, 4, :o6, 9961200
-
1
tz.transition 1970, 10, :o5, 25682400
-
1
tz.transition 2006, 4, :o6, 1143961200
-
1
tz.transition 2006, 10, :o5, 1162101600
-
1
tz.transition 2007, 3, :o6, 1173596400
-
1
tz.transition 2007, 11, :o5, 1194156000
-
1
tz.transition 2008, 3, :o6, 1205046000
-
1
tz.transition 2008, 11, :o5, 1225605600
-
1
tz.transition 2009, 3, :o6, 1236495600
-
1
tz.transition 2009, 11, :o5, 1257055200
-
1
tz.transition 2010, 3, :o6, 1268550000
-
1
tz.transition 2010, 11, :o5, 1289109600
-
1
tz.transition 2011, 3, :o6, 1299999600
-
1
tz.transition 2011, 11, :o5, 1320559200
-
1
tz.transition 2012, 3, :o6, 1331449200
-
1
tz.transition 2012, 11, :o5, 1352008800
-
1
tz.transition 2013, 3, :o6, 1362898800
-
1
tz.transition 2013, 11, :o5, 1383458400
-
1
tz.transition 2014, 3, :o6, 1394348400
-
1
tz.transition 2014, 11, :o5, 1414908000
-
1
tz.transition 2015, 3, :o6, 1425798000
-
1
tz.transition 2015, 11, :o5, 1446357600
-
1
tz.transition 2016, 3, :o6, 1457852400
-
1
tz.transition 2016, 11, :o5, 1478412000
-
1
tz.transition 2017, 3, :o6, 1489302000
-
1
tz.transition 2017, 11, :o5, 1509861600
-
1
tz.transition 2018, 3, :o6, 1520751600
-
1
tz.transition 2018, 11, :o5, 1541311200
-
1
tz.transition 2019, 3, :o6, 1552201200
-
1
tz.transition 2019, 11, :o5, 1572760800
-
1
tz.transition 2020, 3, :o6, 1583650800
-
1
tz.transition 2020, 11, :o5, 1604210400
-
1
tz.transition 2021, 3, :o6, 1615705200
-
1
tz.transition 2021, 11, :o5, 1636264800
-
1
tz.transition 2022, 3, :o6, 1647154800
-
1
tz.transition 2022, 11, :o5, 1667714400
-
1
tz.transition 2023, 3, :o6, 1678604400
-
1
tz.transition 2023, 11, :o5, 1699164000
-
1
tz.transition 2024, 3, :o6, 1710054000
-
1
tz.transition 2024, 11, :o5, 1730613600
-
1
tz.transition 2025, 3, :o6, 1741503600
-
1
tz.transition 2025, 11, :o5, 1762063200
-
1
tz.transition 2026, 3, :o6, 1772953200
-
1
tz.transition 2026, 11, :o5, 1793512800
-
1
tz.transition 2027, 3, :o6, 1805007600
-
1
tz.transition 2027, 11, :o5, 1825567200
-
1
tz.transition 2028, 3, :o6, 1836457200
-
1
tz.transition 2028, 11, :o5, 1857016800
-
1
tz.transition 2029, 3, :o6, 1867906800
-
1
tz.transition 2029, 11, :o5, 1888466400
-
1
tz.transition 2030, 3, :o6, 1899356400
-
1
tz.transition 2030, 11, :o5, 1919916000
-
1
tz.transition 2031, 3, :o6, 1930806000
-
1
tz.transition 2031, 11, :o5, 1951365600
-
1
tz.transition 2032, 3, :o6, 1962860400
-
1
tz.transition 2032, 11, :o5, 1983420000
-
1
tz.transition 2033, 3, :o6, 1994310000
-
1
tz.transition 2033, 11, :o5, 2014869600
-
1
tz.transition 2034, 3, :o6, 2025759600
-
1
tz.transition 2034, 11, :o5, 2046319200
-
1
tz.transition 2035, 3, :o6, 2057209200
-
1
tz.transition 2035, 11, :o5, 2077768800
-
1
tz.transition 2036, 3, :o6, 2088658800
-
1
tz.transition 2036, 11, :o5, 2109218400
-
1
tz.transition 2037, 3, :o6, 2120108400
-
1
tz.transition 2037, 11, :o5, 2140668000
-
1
tz.transition 2038, 3, :o6, 59171923, 24
-
1
tz.transition 2038, 11, :o5, 9862939, 4
-
1
tz.transition 2039, 3, :o6, 59180659, 24
-
1
tz.transition 2039, 11, :o5, 9864395, 4
-
1
tz.transition 2040, 3, :o6, 59189395, 24
-
1
tz.transition 2040, 11, :o5, 9865851, 4
-
1
tz.transition 2041, 3, :o6, 59198131, 24
-
1
tz.transition 2041, 11, :o5, 9867307, 4
-
1
tz.transition 2042, 3, :o6, 59206867, 24
-
1
tz.transition 2042, 11, :o5, 9868763, 4
-
1
tz.transition 2043, 3, :o6, 59215603, 24
-
1
tz.transition 2043, 11, :o5, 9870219, 4
-
1
tz.transition 2044, 3, :o6, 59224507, 24
-
1
tz.transition 2044, 11, :o5, 9871703, 4
-
1
tz.transition 2045, 3, :o6, 59233243, 24
-
1
tz.transition 2045, 11, :o5, 9873159, 4
-
1
tz.transition 2046, 3, :o6, 59241979, 24
-
1
tz.transition 2046, 11, :o5, 9874615, 4
-
1
tz.transition 2047, 3, :o6, 59250715, 24
-
1
tz.transition 2047, 11, :o5, 9876071, 4
-
1
tz.transition 2048, 3, :o6, 59259451, 24
-
1
tz.transition 2048, 11, :o5, 9877527, 4
-
1
tz.transition 2049, 3, :o6, 59268355, 24
-
1
tz.transition 2049, 11, :o5, 9879011, 4
-
1
tz.transition 2050, 3, :o6, 59277091, 24
-
1
tz.transition 2050, 11, :o5, 9880467, 4
-
end
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Juneau
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Juneau' do |tz|
-
1
tz.offset :o0, 54139, 0, :LMT
-
1
tz.offset :o1, -32261, 0, :LMT
-
1
tz.offset :o2, -28800, 0, :PST
-
1
tz.offset :o3, -28800, 3600, :PWT
-
1
tz.offset :o4, -28800, 3600, :PPT
-
1
tz.offset :o5, -28800, 3600, :PDT
-
1
tz.offset :o6, -32400, 3600, :YDT
-
1
tz.offset :o7, -32400, 0, :YST
-
1
tz.offset :o8, -32400, 0, :AKST
-
1
tz.offset :o9, -32400, 3600, :AKDT
-
-
1
tz.transition 1867, 10, :o1, 207641393861, 86400
-
1
tz.transition 1900, 8, :o2, 208677805061, 86400
-
1
tz.transition 1942, 2, :o3, 29164799, 12
-
1
tz.transition 1945, 8, :o4, 58360379, 24
-
1
tz.transition 1945, 9, :o2, 19453831, 8
-
1
tz.transition 1969, 4, :o5, 29284067, 12
-
1
tz.transition 1969, 10, :o2, 19524167, 8
-
1
tz.transition 1970, 4, :o5, 9972000
-
1
tz.transition 1970, 10, :o2, 25693200
-
1
tz.transition 1971, 4, :o5, 41421600
-
1
tz.transition 1971, 10, :o2, 57747600
-
1
tz.transition 1972, 4, :o5, 73476000
-
1
tz.transition 1972, 10, :o2, 89197200
-
1
tz.transition 1973, 4, :o5, 104925600
-
1
tz.transition 1973, 10, :o2, 120646800
-
1
tz.transition 1974, 1, :o5, 126698400
-
1
tz.transition 1974, 10, :o2, 152096400
-
1
tz.transition 1975, 2, :o5, 162381600
-
1
tz.transition 1975, 10, :o2, 183546000
-
1
tz.transition 1976, 4, :o5, 199274400
-
1
tz.transition 1976, 10, :o2, 215600400
-
1
tz.transition 1977, 4, :o5, 230724000
-
1
tz.transition 1977, 10, :o2, 247050000
-
1
tz.transition 1978, 4, :o5, 262778400
-
1
tz.transition 1978, 10, :o2, 278499600
-
1
tz.transition 1979, 4, :o5, 294228000
-
1
tz.transition 1979, 10, :o2, 309949200
-
1
tz.transition 1980, 4, :o6, 325677600
-
1
tz.transition 1980, 10, :o2, 341402400
-
1
tz.transition 1981, 4, :o5, 357127200
-
1
tz.transition 1981, 10, :o2, 372848400
-
1
tz.transition 1982, 4, :o5, 388576800
-
1
tz.transition 1982, 10, :o2, 404902800
-
1
tz.transition 1983, 4, :o5, 420026400
-
1
tz.transition 1983, 10, :o7, 436352400
-
1
tz.transition 1983, 11, :o8, 439030800
-
1
tz.transition 1984, 4, :o9, 452084400
-
1
tz.transition 1984, 10, :o8, 467805600
-
1
tz.transition 1985, 4, :o9, 483534000
-
1
tz.transition 1985, 10, :o8, 499255200
-
1
tz.transition 1986, 4, :o9, 514983600
-
1
tz.transition 1986, 10, :o8, 530704800
-
1
tz.transition 1987, 4, :o9, 544618800
-
1
tz.transition 1987, 10, :o8, 562154400
-
1
tz.transition 1988, 4, :o9, 576068400
-
1
tz.transition 1988, 10, :o8, 594208800
-
1
tz.transition 1989, 4, :o9, 607518000
-
1
tz.transition 1989, 10, :o8, 625658400
-
1
tz.transition 1990, 4, :o9, 638967600
-
1
tz.transition 1990, 10, :o8, 657108000
-
1
tz.transition 1991, 4, :o9, 671022000
-
1
tz.transition 1991, 10, :o8, 688557600
-
1
tz.transition 1992, 4, :o9, 702471600
-
1
tz.transition 1992, 10, :o8, 720007200
-
1
tz.transition 1993, 4, :o9, 733921200
-
1
tz.transition 1993, 10, :o8, 752061600
-
1
tz.transition 1994, 4, :o9, 765370800
-
1
tz.transition 1994, 10, :o8, 783511200
-
1
tz.transition 1995, 4, :o9, 796820400
-
1
tz.transition 1995, 10, :o8, 814960800
-
1
tz.transition 1996, 4, :o9, 828874800
-
1
tz.transition 1996, 10, :o8, 846410400
-
1
tz.transition 1997, 4, :o9, 860324400
-
1
tz.transition 1997, 10, :o8, 877860000
-
1
tz.transition 1998, 4, :o9, 891774000
-
1
tz.transition 1998, 10, :o8, 909309600
-
1
tz.transition 1999, 4, :o9, 923223600
-
1
tz.transition 1999, 10, :o8, 941364000
-
1
tz.transition 2000, 4, :o9, 954673200
-
1
tz.transition 2000, 10, :o8, 972813600
-
1
tz.transition 2001, 4, :o9, 986122800
-
1
tz.transition 2001, 10, :o8, 1004263200
-
1
tz.transition 2002, 4, :o9, 1018177200
-
1
tz.transition 2002, 10, :o8, 1035712800
-
1
tz.transition 2003, 4, :o9, 1049626800
-
1
tz.transition 2003, 10, :o8, 1067162400
-
1
tz.transition 2004, 4, :o9, 1081076400
-
1
tz.transition 2004, 10, :o8, 1099216800
-
1
tz.transition 2005, 4, :o9, 1112526000
-
1
tz.transition 2005, 10, :o8, 1130666400
-
1
tz.transition 2006, 4, :o9, 1143975600
-
1
tz.transition 2006, 10, :o8, 1162116000
-
1
tz.transition 2007, 3, :o9, 1173610800
-
1
tz.transition 2007, 11, :o8, 1194170400
-
1
tz.transition 2008, 3, :o9, 1205060400
-
1
tz.transition 2008, 11, :o8, 1225620000
-
1
tz.transition 2009, 3, :o9, 1236510000
-
1
tz.transition 2009, 11, :o8, 1257069600
-
1
tz.transition 2010, 3, :o9, 1268564400
-
1
tz.transition 2010, 11, :o8, 1289124000
-
1
tz.transition 2011, 3, :o9, 1300014000
-
1
tz.transition 2011, 11, :o8, 1320573600
-
1
tz.transition 2012, 3, :o9, 1331463600
-
1
tz.transition 2012, 11, :o8, 1352023200
-
1
tz.transition 2013, 3, :o9, 1362913200
-
1
tz.transition 2013, 11, :o8, 1383472800
-
1
tz.transition 2014, 3, :o9, 1394362800
-
1
tz.transition 2014, 11, :o8, 1414922400
-
1
tz.transition 2015, 3, :o9, 1425812400
-
1
tz.transition 2015, 11, :o8, 1446372000
-
1
tz.transition 2016, 3, :o9, 1457866800
-
1
tz.transition 2016, 11, :o8, 1478426400
-
1
tz.transition 2017, 3, :o9, 1489316400
-
1
tz.transition 2017, 11, :o8, 1509876000
-
1
tz.transition 2018, 3, :o9, 1520766000
-
1
tz.transition 2018, 11, :o8, 1541325600
-
1
tz.transition 2019, 3, :o9, 1552215600
-
1
tz.transition 2019, 11, :o8, 1572775200
-
1
tz.transition 2020, 3, :o9, 1583665200
-
1
tz.transition 2020, 11, :o8, 1604224800
-
1
tz.transition 2021, 3, :o9, 1615719600
-
1
tz.transition 2021, 11, :o8, 1636279200
-
1
tz.transition 2022, 3, :o9, 1647169200
-
1
tz.transition 2022, 11, :o8, 1667728800
-
1
tz.transition 2023, 3, :o9, 1678618800
-
1
tz.transition 2023, 11, :o8, 1699178400
-
1
tz.transition 2024, 3, :o9, 1710068400
-
1
tz.transition 2024, 11, :o8, 1730628000
-
1
tz.transition 2025, 3, :o9, 1741518000
-
1
tz.transition 2025, 11, :o8, 1762077600
-
1
tz.transition 2026, 3, :o9, 1772967600
-
1
tz.transition 2026, 11, :o8, 1793527200
-
1
tz.transition 2027, 3, :o9, 1805022000
-
1
tz.transition 2027, 11, :o8, 1825581600
-
1
tz.transition 2028, 3, :o9, 1836471600
-
1
tz.transition 2028, 11, :o8, 1857031200
-
1
tz.transition 2029, 3, :o9, 1867921200
-
1
tz.transition 2029, 11, :o8, 1888480800
-
1
tz.transition 2030, 3, :o9, 1899370800
-
1
tz.transition 2030, 11, :o8, 1919930400
-
1
tz.transition 2031, 3, :o9, 1930820400
-
1
tz.transition 2031, 11, :o8, 1951380000
-
1
tz.transition 2032, 3, :o9, 1962874800
-
1
tz.transition 2032, 11, :o8, 1983434400
-
1
tz.transition 2033, 3, :o9, 1994324400
-
1
tz.transition 2033, 11, :o8, 2014884000
-
1
tz.transition 2034, 3, :o9, 2025774000
-
1
tz.transition 2034, 11, :o8, 2046333600
-
1
tz.transition 2035, 3, :o9, 2057223600
-
1
tz.transition 2035, 11, :o8, 2077783200
-
1
tz.transition 2036, 3, :o9, 2088673200
-
1
tz.transition 2036, 11, :o8, 2109232800
-
1
tz.transition 2037, 3, :o9, 2120122800
-
1
tz.transition 2037, 11, :o8, 2140682400
-
1
tz.transition 2038, 3, :o9, 59171927, 24
-
1
tz.transition 2038, 11, :o8, 29588819, 12
-
1
tz.transition 2039, 3, :o9, 59180663, 24
-
1
tz.transition 2039, 11, :o8, 29593187, 12
-
1
tz.transition 2040, 3, :o9, 59189399, 24
-
1
tz.transition 2040, 11, :o8, 29597555, 12
-
1
tz.transition 2041, 3, :o9, 59198135, 24
-
1
tz.transition 2041, 11, :o8, 29601923, 12
-
1
tz.transition 2042, 3, :o9, 59206871, 24
-
1
tz.transition 2042, 11, :o8, 29606291, 12
-
1
tz.transition 2043, 3, :o9, 59215607, 24
-
1
tz.transition 2043, 11, :o8, 29610659, 12
-
1
tz.transition 2044, 3, :o9, 59224511, 24
-
1
tz.transition 2044, 11, :o8, 29615111, 12
-
1
tz.transition 2045, 3, :o9, 59233247, 24
-
1
tz.transition 2045, 11, :o8, 29619479, 12
-
1
tz.transition 2046, 3, :o9, 59241983, 24
-
1
tz.transition 2046, 11, :o8, 29623847, 12
-
1
tz.transition 2047, 3, :o9, 59250719, 24
-
1
tz.transition 2047, 11, :o8, 29628215, 12
-
1
tz.transition 2048, 3, :o9, 59259455, 24
-
1
tz.transition 2048, 11, :o8, 29632583, 12
-
1
tz.transition 2049, 3, :o9, 59268359, 24
-
1
tz.transition 2049, 11, :o8, 29637035, 12
-
1
tz.transition 2050, 3, :o9, 59277095, 24
-
1
tz.transition 2050, 11, :o8, 29641403, 12
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module La_Paz
-
1
include TimezoneDefinition
-
-
1
timezone 'America/La_Paz' do |tz|
-
1
tz.offset :o0, -16356, 0, :LMT
-
1
tz.offset :o1, -16356, 0, :CMT
-
1
tz.offset :o2, -16356, 3600, :BOST
-
1
tz.offset :o3, -14400, 0, :BOT
-
-
1
tz.transition 1890, 1, :o1, 17361854563, 7200
-
1
tz.transition 1931, 10, :o2, 17471733763, 7200
-
1
tz.transition 1932, 3, :o3, 17472871063, 7200
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Lima
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Lima' do |tz|
-
1
tz.offset :o0, -18492, 0, :LMT
-
1
tz.offset :o1, -18516, 0, :LMT
-
1
tz.offset :o2, -18000, 0, :PET
-
1
tz.offset :o3, -18000, 3600, :PEST
-
-
1
tz.transition 1890, 1, :o1, 17361854741, 7200
-
1
tz.transition 1908, 7, :o2, 17410685143, 7200
-
1
tz.transition 1938, 1, :o3, 58293593, 24
-
1
tz.transition 1938, 4, :o2, 7286969, 3
-
1
tz.transition 1938, 9, :o3, 58300001, 24
-
1
tz.transition 1939, 3, :o2, 7288046, 3
-
1
tz.transition 1939, 9, :o3, 58308737, 24
-
1
tz.transition 1940, 3, :o2, 7289138, 3
-
1
tz.transition 1986, 1, :o3, 504939600
-
1
tz.transition 1986, 4, :o2, 512712000
-
1
tz.transition 1987, 1, :o3, 536475600
-
1
tz.transition 1987, 4, :o2, 544248000
-
1
tz.transition 1990, 1, :o3, 631170000
-
1
tz.transition 1990, 4, :o2, 638942400
-
1
tz.transition 1994, 1, :o3, 757400400
-
1
tz.transition 1994, 4, :o2, 765172800
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Los_Angeles
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Los_Angeles' do |tz|
-
1
tz.offset :o0, -28378, 0, :LMT
-
1
tz.offset :o1, -28800, 0, :PST
-
1
tz.offset :o2, -28800, 3600, :PDT
-
1
tz.offset :o3, -28800, 3600, :PWT
-
1
tz.offset :o4, -28800, 3600, :PPT
-
-
1
tz.transition 1883, 11, :o1, 7227400, 3
-
1
tz.transition 1918, 3, :o2, 29060207, 12
-
1
tz.transition 1918, 10, :o1, 19375151, 8
-
1
tz.transition 1919, 3, :o2, 29064575, 12
-
1
tz.transition 1919, 10, :o1, 19378063, 8
-
1
tz.transition 1942, 2, :o3, 29164799, 12
-
1
tz.transition 1945, 8, :o4, 58360379, 24
-
1
tz.transition 1945, 9, :o1, 19453831, 8
-
1
tz.transition 1948, 3, :o2, 29191499, 12
-
1
tz.transition 1949, 1, :o1, 19463343, 8
-
1
tz.transition 1950, 4, :o2, 29200823, 12
-
1
tz.transition 1950, 9, :o1, 19468391, 8
-
1
tz.transition 1951, 4, :o2, 29205191, 12
-
1
tz.transition 1951, 9, :o1, 19471359, 8
-
1
tz.transition 1952, 4, :o2, 29209559, 12
-
1
tz.transition 1952, 9, :o1, 19474271, 8
-
1
tz.transition 1953, 4, :o2, 29213927, 12
-
1
tz.transition 1953, 9, :o1, 19477183, 8
-
1
tz.transition 1954, 4, :o2, 29218295, 12
-
1
tz.transition 1954, 9, :o1, 19480095, 8
-
1
tz.transition 1955, 4, :o2, 29222663, 12
-
1
tz.transition 1955, 9, :o1, 19483007, 8
-
1
tz.transition 1956, 4, :o2, 29227115, 12
-
1
tz.transition 1956, 9, :o1, 19485975, 8
-
1
tz.transition 1957, 4, :o2, 29231483, 12
-
1
tz.transition 1957, 9, :o1, 19488887, 8
-
1
tz.transition 1958, 4, :o2, 29235851, 12
-
1
tz.transition 1958, 9, :o1, 19491799, 8
-
1
tz.transition 1959, 4, :o2, 29240219, 12
-
1
tz.transition 1959, 9, :o1, 19494711, 8
-
1
tz.transition 1960, 4, :o2, 29244587, 12
-
1
tz.transition 1960, 9, :o1, 19497623, 8
-
1
tz.transition 1961, 4, :o2, 29249039, 12
-
1
tz.transition 1961, 9, :o1, 19500535, 8
-
1
tz.transition 1962, 4, :o2, 29253407, 12
-
1
tz.transition 1962, 10, :o1, 19503727, 8
-
1
tz.transition 1963, 4, :o2, 29257775, 12
-
1
tz.transition 1963, 10, :o1, 19506639, 8
-
1
tz.transition 1964, 4, :o2, 29262143, 12
-
1
tz.transition 1964, 10, :o1, 19509551, 8
-
1
tz.transition 1965, 4, :o2, 29266511, 12
-
1
tz.transition 1965, 10, :o1, 19512519, 8
-
1
tz.transition 1966, 4, :o2, 29270879, 12
-
1
tz.transition 1966, 10, :o1, 19515431, 8
-
1
tz.transition 1967, 4, :o2, 29275331, 12
-
1
tz.transition 1967, 10, :o1, 19518343, 8
-
1
tz.transition 1968, 4, :o2, 29279699, 12
-
1
tz.transition 1968, 10, :o1, 19521255, 8
-
1
tz.transition 1969, 4, :o2, 29284067, 12
-
1
tz.transition 1969, 10, :o1, 19524167, 8
-
1
tz.transition 1970, 4, :o2, 9972000
-
1
tz.transition 1970, 10, :o1, 25693200
-
1
tz.transition 1971, 4, :o2, 41421600
-
1
tz.transition 1971, 10, :o1, 57747600
-
1
tz.transition 1972, 4, :o2, 73476000
-
1
tz.transition 1972, 10, :o1, 89197200
-
1
tz.transition 1973, 4, :o2, 104925600
-
1
tz.transition 1973, 10, :o1, 120646800
-
1
tz.transition 1974, 1, :o2, 126698400
-
1
tz.transition 1974, 10, :o1, 152096400
-
1
tz.transition 1975, 2, :o2, 162381600
-
1
tz.transition 1975, 10, :o1, 183546000
-
1
tz.transition 1976, 4, :o2, 199274400
-
1
tz.transition 1976, 10, :o1, 215600400
-
1
tz.transition 1977, 4, :o2, 230724000
-
1
tz.transition 1977, 10, :o1, 247050000
-
1
tz.transition 1978, 4, :o2, 262778400
-
1
tz.transition 1978, 10, :o1, 278499600
-
1
tz.transition 1979, 4, :o2, 294228000
-
1
tz.transition 1979, 10, :o1, 309949200
-
1
tz.transition 1980, 4, :o2, 325677600
-
1
tz.transition 1980, 10, :o1, 341398800
-
1
tz.transition 1981, 4, :o2, 357127200
-
1
tz.transition 1981, 10, :o1, 372848400
-
1
tz.transition 1982, 4, :o2, 388576800
-
1
tz.transition 1982, 10, :o1, 404902800
-
1
tz.transition 1983, 4, :o2, 420026400
-
1
tz.transition 1983, 10, :o1, 436352400
-
1
tz.transition 1984, 4, :o2, 452080800
-
1
tz.transition 1984, 10, :o1, 467802000
-
1
tz.transition 1985, 4, :o2, 483530400
-
1
tz.transition 1985, 10, :o1, 499251600
-
1
tz.transition 1986, 4, :o2, 514980000
-
1
tz.transition 1986, 10, :o1, 530701200
-
1
tz.transition 1987, 4, :o2, 544615200
-
1
tz.transition 1987, 10, :o1, 562150800
-
1
tz.transition 1988, 4, :o2, 576064800
-
1
tz.transition 1988, 10, :o1, 594205200
-
1
tz.transition 1989, 4, :o2, 607514400
-
1
tz.transition 1989, 10, :o1, 625654800
-
1
tz.transition 1990, 4, :o2, 638964000
-
1
tz.transition 1990, 10, :o1, 657104400
-
1
tz.transition 1991, 4, :o2, 671018400
-
1
tz.transition 1991, 10, :o1, 688554000
-
1
tz.transition 1992, 4, :o2, 702468000
-
1
tz.transition 1992, 10, :o1, 720003600
-
1
tz.transition 1993, 4, :o2, 733917600
-
1
tz.transition 1993, 10, :o1, 752058000
-
1
tz.transition 1994, 4, :o2, 765367200
-
1
tz.transition 1994, 10, :o1, 783507600
-
1
tz.transition 1995, 4, :o2, 796816800
-
1
tz.transition 1995, 10, :o1, 814957200
-
1
tz.transition 1996, 4, :o2, 828871200
-
1
tz.transition 1996, 10, :o1, 846406800
-
1
tz.transition 1997, 4, :o2, 860320800
-
1
tz.transition 1997, 10, :o1, 877856400
-
1
tz.transition 1998, 4, :o2, 891770400
-
1
tz.transition 1998, 10, :o1, 909306000
-
1
tz.transition 1999, 4, :o2, 923220000
-
1
tz.transition 1999, 10, :o1, 941360400
-
1
tz.transition 2000, 4, :o2, 954669600
-
1
tz.transition 2000, 10, :o1, 972810000
-
1
tz.transition 2001, 4, :o2, 986119200
-
1
tz.transition 2001, 10, :o1, 1004259600
-
1
tz.transition 2002, 4, :o2, 1018173600
-
1
tz.transition 2002, 10, :o1, 1035709200
-
1
tz.transition 2003, 4, :o2, 1049623200
-
1
tz.transition 2003, 10, :o1, 1067158800
-
1
tz.transition 2004, 4, :o2, 1081072800
-
1
tz.transition 2004, 10, :o1, 1099213200
-
1
tz.transition 2005, 4, :o2, 1112522400
-
1
tz.transition 2005, 10, :o1, 1130662800
-
1
tz.transition 2006, 4, :o2, 1143972000
-
1
tz.transition 2006, 10, :o1, 1162112400
-
1
tz.transition 2007, 3, :o2, 1173607200
-
1
tz.transition 2007, 11, :o1, 1194166800
-
1
tz.transition 2008, 3, :o2, 1205056800
-
1
tz.transition 2008, 11, :o1, 1225616400
-
1
tz.transition 2009, 3, :o2, 1236506400
-
1
tz.transition 2009, 11, :o1, 1257066000
-
1
tz.transition 2010, 3, :o2, 1268560800
-
1
tz.transition 2010, 11, :o1, 1289120400
-
1
tz.transition 2011, 3, :o2, 1300010400
-
1
tz.transition 2011, 11, :o1, 1320570000
-
1
tz.transition 2012, 3, :o2, 1331460000
-
1
tz.transition 2012, 11, :o1, 1352019600
-
1
tz.transition 2013, 3, :o2, 1362909600
-
1
tz.transition 2013, 11, :o1, 1383469200
-
1
tz.transition 2014, 3, :o2, 1394359200
-
1
tz.transition 2014, 11, :o1, 1414918800
-
1
tz.transition 2015, 3, :o2, 1425808800
-
1
tz.transition 2015, 11, :o1, 1446368400
-
1
tz.transition 2016, 3, :o2, 1457863200
-
1
tz.transition 2016, 11, :o1, 1478422800
-
1
tz.transition 2017, 3, :o2, 1489312800
-
1
tz.transition 2017, 11, :o1, 1509872400
-
1
tz.transition 2018, 3, :o2, 1520762400
-
1
tz.transition 2018, 11, :o1, 1541322000
-
1
tz.transition 2019, 3, :o2, 1552212000
-
1
tz.transition 2019, 11, :o1, 1572771600
-
1
tz.transition 2020, 3, :o2, 1583661600
-
1
tz.transition 2020, 11, :o1, 1604221200
-
1
tz.transition 2021, 3, :o2, 1615716000
-
1
tz.transition 2021, 11, :o1, 1636275600
-
1
tz.transition 2022, 3, :o2, 1647165600
-
1
tz.transition 2022, 11, :o1, 1667725200
-
1
tz.transition 2023, 3, :o2, 1678615200
-
1
tz.transition 2023, 11, :o1, 1699174800
-
1
tz.transition 2024, 3, :o2, 1710064800
-
1
tz.transition 2024, 11, :o1, 1730624400
-
1
tz.transition 2025, 3, :o2, 1741514400
-
1
tz.transition 2025, 11, :o1, 1762074000
-
1
tz.transition 2026, 3, :o2, 1772964000
-
1
tz.transition 2026, 11, :o1, 1793523600
-
1
tz.transition 2027, 3, :o2, 1805018400
-
1
tz.transition 2027, 11, :o1, 1825578000
-
1
tz.transition 2028, 3, :o2, 1836468000
-
1
tz.transition 2028, 11, :o1, 1857027600
-
1
tz.transition 2029, 3, :o2, 1867917600
-
1
tz.transition 2029, 11, :o1, 1888477200
-
1
tz.transition 2030, 3, :o2, 1899367200
-
1
tz.transition 2030, 11, :o1, 1919926800
-
1
tz.transition 2031, 3, :o2, 1930816800
-
1
tz.transition 2031, 11, :o1, 1951376400
-
1
tz.transition 2032, 3, :o2, 1962871200
-
1
tz.transition 2032, 11, :o1, 1983430800
-
1
tz.transition 2033, 3, :o2, 1994320800
-
1
tz.transition 2033, 11, :o1, 2014880400
-
1
tz.transition 2034, 3, :o2, 2025770400
-
1
tz.transition 2034, 11, :o1, 2046330000
-
1
tz.transition 2035, 3, :o2, 2057220000
-
1
tz.transition 2035, 11, :o1, 2077779600
-
1
tz.transition 2036, 3, :o2, 2088669600
-
1
tz.transition 2036, 11, :o1, 2109229200
-
1
tz.transition 2037, 3, :o2, 2120119200
-
1
tz.transition 2037, 11, :o1, 2140678800
-
1
tz.transition 2038, 3, :o2, 29585963, 12
-
1
tz.transition 2038, 11, :o1, 19725879, 8
-
1
tz.transition 2039, 3, :o2, 29590331, 12
-
1
tz.transition 2039, 11, :o1, 19728791, 8
-
1
tz.transition 2040, 3, :o2, 29594699, 12
-
1
tz.transition 2040, 11, :o1, 19731703, 8
-
1
tz.transition 2041, 3, :o2, 29599067, 12
-
1
tz.transition 2041, 11, :o1, 19734615, 8
-
1
tz.transition 2042, 3, :o2, 29603435, 12
-
1
tz.transition 2042, 11, :o1, 19737527, 8
-
1
tz.transition 2043, 3, :o2, 29607803, 12
-
1
tz.transition 2043, 11, :o1, 19740439, 8
-
1
tz.transition 2044, 3, :o2, 29612255, 12
-
1
tz.transition 2044, 11, :o1, 19743407, 8
-
1
tz.transition 2045, 3, :o2, 29616623, 12
-
1
tz.transition 2045, 11, :o1, 19746319, 8
-
1
tz.transition 2046, 3, :o2, 29620991, 12
-
1
tz.transition 2046, 11, :o1, 19749231, 8
-
1
tz.transition 2047, 3, :o2, 29625359, 12
-
1
tz.transition 2047, 11, :o1, 19752143, 8
-
1
tz.transition 2048, 3, :o2, 29629727, 12
-
1
tz.transition 2048, 11, :o1, 19755055, 8
-
1
tz.transition 2049, 3, :o2, 29634179, 12
-
1
tz.transition 2049, 11, :o1, 19758023, 8
-
1
tz.transition 2050, 3, :o2, 29638547, 12
-
1
tz.transition 2050, 11, :o1, 19760935, 8
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Mazatlan
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Mazatlan' do |tz|
-
1
tz.offset :o0, -25540, 0, :LMT
-
1
tz.offset :o1, -25200, 0, :MST
-
1
tz.offset :o2, -21600, 0, :CST
-
1
tz.offset :o3, -28800, 0, :PST
-
1
tz.offset :o4, -25200, 3600, :MDT
-
-
1
tz.transition 1922, 1, :o1, 58153339, 24
-
1
tz.transition 1927, 6, :o2, 9700171, 4
-
1
tz.transition 1930, 11, :o1, 9705183, 4
-
1
tz.transition 1931, 5, :o2, 9705855, 4
-
1
tz.transition 1931, 10, :o1, 9706463, 4
-
1
tz.transition 1932, 4, :o2, 58243171, 24
-
1
tz.transition 1942, 4, :o1, 9721895, 4
-
1
tz.transition 1949, 1, :o3, 58390339, 24
-
1
tz.transition 1970, 1, :o1, 28800
-
1
tz.transition 1996, 4, :o4, 828867600
-
1
tz.transition 1996, 10, :o1, 846403200
-
1
tz.transition 1997, 4, :o4, 860317200
-
1
tz.transition 1997, 10, :o1, 877852800
-
1
tz.transition 1998, 4, :o4, 891766800
-
1
tz.transition 1998, 10, :o1, 909302400
-
1
tz.transition 1999, 4, :o4, 923216400
-
1
tz.transition 1999, 10, :o1, 941356800
-
1
tz.transition 2000, 4, :o4, 954666000
-
1
tz.transition 2000, 10, :o1, 972806400
-
1
tz.transition 2001, 5, :o4, 989139600
-
1
tz.transition 2001, 9, :o1, 1001836800
-
1
tz.transition 2002, 4, :o4, 1018170000
-
1
tz.transition 2002, 10, :o1, 1035705600
-
1
tz.transition 2003, 4, :o4, 1049619600
-
1
tz.transition 2003, 10, :o1, 1067155200
-
1
tz.transition 2004, 4, :o4, 1081069200
-
1
tz.transition 2004, 10, :o1, 1099209600
-
1
tz.transition 2005, 4, :o4, 1112518800
-
1
tz.transition 2005, 10, :o1, 1130659200
-
1
tz.transition 2006, 4, :o4, 1143968400
-
1
tz.transition 2006, 10, :o1, 1162108800
-
1
tz.transition 2007, 4, :o4, 1175418000
-
1
tz.transition 2007, 10, :o1, 1193558400
-
1
tz.transition 2008, 4, :o4, 1207472400
-
1
tz.transition 2008, 10, :o1, 1225008000
-
1
tz.transition 2009, 4, :o4, 1238922000
-
1
tz.transition 2009, 10, :o1, 1256457600
-
1
tz.transition 2010, 4, :o4, 1270371600
-
1
tz.transition 2010, 10, :o1, 1288512000
-
1
tz.transition 2011, 4, :o4, 1301821200
-
1
tz.transition 2011, 10, :o1, 1319961600
-
1
tz.transition 2012, 4, :o4, 1333270800
-
1
tz.transition 2012, 10, :o1, 1351411200
-
1
tz.transition 2013, 4, :o4, 1365325200
-
1
tz.transition 2013, 10, :o1, 1382860800
-
1
tz.transition 2014, 4, :o4, 1396774800
-
1
tz.transition 2014, 10, :o1, 1414310400
-
1
tz.transition 2015, 4, :o4, 1428224400
-
1
tz.transition 2015, 10, :o1, 1445760000
-
1
tz.transition 2016, 4, :o4, 1459674000
-
1
tz.transition 2016, 10, :o1, 1477814400
-
1
tz.transition 2017, 4, :o4, 1491123600
-
1
tz.transition 2017, 10, :o1, 1509264000
-
1
tz.transition 2018, 4, :o4, 1522573200
-
1
tz.transition 2018, 10, :o1, 1540713600
-
1
tz.transition 2019, 4, :o4, 1554627600
-
1
tz.transition 2019, 10, :o1, 1572163200
-
1
tz.transition 2020, 4, :o4, 1586077200
-
1
tz.transition 2020, 10, :o1, 1603612800
-
1
tz.transition 2021, 4, :o4, 1617526800
-
1
tz.transition 2021, 10, :o1, 1635667200
-
1
tz.transition 2022, 4, :o4, 1648976400
-
1
tz.transition 2022, 10, :o1, 1667116800
-
1
tz.transition 2023, 4, :o4, 1680426000
-
1
tz.transition 2023, 10, :o1, 1698566400
-
1
tz.transition 2024, 4, :o4, 1712480400
-
1
tz.transition 2024, 10, :o1, 1730016000
-
1
tz.transition 2025, 4, :o4, 1743930000
-
1
tz.transition 2025, 10, :o1, 1761465600
-
1
tz.transition 2026, 4, :o4, 1775379600
-
1
tz.transition 2026, 10, :o1, 1792915200
-
1
tz.transition 2027, 4, :o4, 1806829200
-
1
tz.transition 2027, 10, :o1, 1824969600
-
1
tz.transition 2028, 4, :o4, 1838278800
-
1
tz.transition 2028, 10, :o1, 1856419200
-
1
tz.transition 2029, 4, :o4, 1869728400
-
1
tz.transition 2029, 10, :o1, 1887868800
-
1
tz.transition 2030, 4, :o4, 1901782800
-
1
tz.transition 2030, 10, :o1, 1919318400
-
1
tz.transition 2031, 4, :o4, 1933232400
-
1
tz.transition 2031, 10, :o1, 1950768000
-
1
tz.transition 2032, 4, :o4, 1964682000
-
1
tz.transition 2032, 10, :o1, 1982822400
-
1
tz.transition 2033, 4, :o4, 1996131600
-
1
tz.transition 2033, 10, :o1, 2014272000
-
1
tz.transition 2034, 4, :o4, 2027581200
-
1
tz.transition 2034, 10, :o1, 2045721600
-
1
tz.transition 2035, 4, :o4, 2059030800
-
1
tz.transition 2035, 10, :o1, 2077171200
-
1
tz.transition 2036, 4, :o4, 2091085200
-
1
tz.transition 2036, 10, :o1, 2108620800
-
1
tz.transition 2037, 4, :o4, 2122534800
-
1
tz.transition 2037, 10, :o1, 2140070400
-
1
tz.transition 2038, 4, :o4, 19724143, 8
-
1
tz.transition 2038, 10, :o1, 14794367, 6
-
1
tz.transition 2039, 4, :o4, 19727055, 8
-
1
tz.transition 2039, 10, :o1, 14796551, 6
-
1
tz.transition 2040, 4, :o4, 19729967, 8
-
1
tz.transition 2040, 10, :o1, 14798735, 6
-
1
tz.transition 2041, 4, :o4, 19732935, 8
-
1
tz.transition 2041, 10, :o1, 14800919, 6
-
1
tz.transition 2042, 4, :o4, 19735847, 8
-
1
tz.transition 2042, 10, :o1, 14803103, 6
-
1
tz.transition 2043, 4, :o4, 19738759, 8
-
1
tz.transition 2043, 10, :o1, 14805287, 6
-
1
tz.transition 2044, 4, :o4, 19741671, 8
-
1
tz.transition 2044, 10, :o1, 14807513, 6
-
1
tz.transition 2045, 4, :o4, 19744583, 8
-
1
tz.transition 2045, 10, :o1, 14809697, 6
-
1
tz.transition 2046, 4, :o4, 19747495, 8
-
1
tz.transition 2046, 10, :o1, 14811881, 6
-
1
tz.transition 2047, 4, :o4, 19750463, 8
-
1
tz.transition 2047, 10, :o1, 14814065, 6
-
1
tz.transition 2048, 4, :o4, 19753375, 8
-
1
tz.transition 2048, 10, :o1, 14816249, 6
-
1
tz.transition 2049, 4, :o4, 19756287, 8
-
1
tz.transition 2049, 10, :o1, 14818475, 6
-
1
tz.transition 2050, 4, :o4, 19759199, 8
-
1
tz.transition 2050, 10, :o1, 14820659, 6
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Mexico_City
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Mexico_City' do |tz|
-
1
tz.offset :o0, -23796, 0, :LMT
-
1
tz.offset :o1, -25200, 0, :MST
-
1
tz.offset :o2, -21600, 0, :CST
-
1
tz.offset :o3, -21600, 3600, :CDT
-
1
tz.offset :o4, -21600, 3600, :CWT
-
-
1
tz.transition 1922, 1, :o1, 58153339, 24
-
1
tz.transition 1927, 6, :o2, 9700171, 4
-
1
tz.transition 1930, 11, :o1, 9705183, 4
-
1
tz.transition 1931, 5, :o2, 9705855, 4
-
1
tz.transition 1931, 10, :o1, 9706463, 4
-
1
tz.transition 1932, 4, :o2, 58243171, 24
-
1
tz.transition 1939, 2, :o3, 9717199, 4
-
1
tz.transition 1939, 6, :o2, 58306553, 24
-
1
tz.transition 1940, 12, :o3, 9719891, 4
-
1
tz.transition 1941, 4, :o2, 58322057, 24
-
1
tz.transition 1943, 12, :o4, 9724299, 4
-
1
tz.transition 1944, 5, :o2, 58349081, 24
-
1
tz.transition 1950, 2, :o3, 9733299, 4
-
1
tz.transition 1950, 7, :o2, 58403825, 24
-
1
tz.transition 1996, 4, :o3, 828864000
-
1
tz.transition 1996, 10, :o2, 846399600
-
1
tz.transition 1997, 4, :o3, 860313600
-
1
tz.transition 1997, 10, :o2, 877849200
-
1
tz.transition 1998, 4, :o3, 891763200
-
1
tz.transition 1998, 10, :o2, 909298800
-
1
tz.transition 1999, 4, :o3, 923212800
-
1
tz.transition 1999, 10, :o2, 941353200
-
1
tz.transition 2000, 4, :o3, 954662400
-
1
tz.transition 2000, 10, :o2, 972802800
-
1
tz.transition 2001, 5, :o3, 989136000
-
1
tz.transition 2001, 9, :o2, 1001833200
-
1
tz.transition 2002, 4, :o3, 1018166400
-
1
tz.transition 2002, 10, :o2, 1035702000
-
1
tz.transition 2003, 4, :o3, 1049616000
-
1
tz.transition 2003, 10, :o2, 1067151600
-
1
tz.transition 2004, 4, :o3, 1081065600
-
1
tz.transition 2004, 10, :o2, 1099206000
-
1
tz.transition 2005, 4, :o3, 1112515200
-
1
tz.transition 2005, 10, :o2, 1130655600
-
1
tz.transition 2006, 4, :o3, 1143964800
-
1
tz.transition 2006, 10, :o2, 1162105200
-
1
tz.transition 2007, 4, :o3, 1175414400
-
1
tz.transition 2007, 10, :o2, 1193554800
-
1
tz.transition 2008, 4, :o3, 1207468800
-
1
tz.transition 2008, 10, :o2, 1225004400
-
1
tz.transition 2009, 4, :o3, 1238918400
-
1
tz.transition 2009, 10, :o2, 1256454000
-
1
tz.transition 2010, 4, :o3, 1270368000
-
1
tz.transition 2010, 10, :o2, 1288508400
-
1
tz.transition 2011, 4, :o3, 1301817600
-
1
tz.transition 2011, 10, :o2, 1319958000
-
1
tz.transition 2012, 4, :o3, 1333267200
-
1
tz.transition 2012, 10, :o2, 1351407600
-
1
tz.transition 2013, 4, :o3, 1365321600
-
1
tz.transition 2013, 10, :o2, 1382857200
-
1
tz.transition 2014, 4, :o3, 1396771200
-
1
tz.transition 2014, 10, :o2, 1414306800
-
1
tz.transition 2015, 4, :o3, 1428220800
-
1
tz.transition 2015, 10, :o2, 1445756400
-
1
tz.transition 2016, 4, :o3, 1459670400
-
1
tz.transition 2016, 10, :o2, 1477810800
-
1
tz.transition 2017, 4, :o3, 1491120000
-
1
tz.transition 2017, 10, :o2, 1509260400
-
1
tz.transition 2018, 4, :o3, 1522569600
-
1
tz.transition 2018, 10, :o2, 1540710000
-
1
tz.transition 2019, 4, :o3, 1554624000
-
1
tz.transition 2019, 10, :o2, 1572159600
-
1
tz.transition 2020, 4, :o3, 1586073600
-
1
tz.transition 2020, 10, :o2, 1603609200
-
1
tz.transition 2021, 4, :o3, 1617523200
-
1
tz.transition 2021, 10, :o2, 1635663600
-
1
tz.transition 2022, 4, :o3, 1648972800
-
1
tz.transition 2022, 10, :o2, 1667113200
-
1
tz.transition 2023, 4, :o3, 1680422400
-
1
tz.transition 2023, 10, :o2, 1698562800
-
1
tz.transition 2024, 4, :o3, 1712476800
-
1
tz.transition 2024, 10, :o2, 1730012400
-
1
tz.transition 2025, 4, :o3, 1743926400
-
1
tz.transition 2025, 10, :o2, 1761462000
-
1
tz.transition 2026, 4, :o3, 1775376000
-
1
tz.transition 2026, 10, :o2, 1792911600
-
1
tz.transition 2027, 4, :o3, 1806825600
-
1
tz.transition 2027, 10, :o2, 1824966000
-
1
tz.transition 2028, 4, :o3, 1838275200
-
1
tz.transition 2028, 10, :o2, 1856415600
-
1
tz.transition 2029, 4, :o3, 1869724800
-
1
tz.transition 2029, 10, :o2, 1887865200
-
1
tz.transition 2030, 4, :o3, 1901779200
-
1
tz.transition 2030, 10, :o2, 1919314800
-
1
tz.transition 2031, 4, :o3, 1933228800
-
1
tz.transition 2031, 10, :o2, 1950764400
-
1
tz.transition 2032, 4, :o3, 1964678400
-
1
tz.transition 2032, 10, :o2, 1982818800
-
1
tz.transition 2033, 4, :o3, 1996128000
-
1
tz.transition 2033, 10, :o2, 2014268400
-
1
tz.transition 2034, 4, :o3, 2027577600
-
1
tz.transition 2034, 10, :o2, 2045718000
-
1
tz.transition 2035, 4, :o3, 2059027200
-
1
tz.transition 2035, 10, :o2, 2077167600
-
1
tz.transition 2036, 4, :o3, 2091081600
-
1
tz.transition 2036, 10, :o2, 2108617200
-
1
tz.transition 2037, 4, :o3, 2122531200
-
1
tz.transition 2037, 10, :o2, 2140066800
-
1
tz.transition 2038, 4, :o3, 14793107, 6
-
1
tz.transition 2038, 10, :o2, 59177467, 24
-
1
tz.transition 2039, 4, :o3, 14795291, 6
-
1
tz.transition 2039, 10, :o2, 59186203, 24
-
1
tz.transition 2040, 4, :o3, 14797475, 6
-
1
tz.transition 2040, 10, :o2, 59194939, 24
-
1
tz.transition 2041, 4, :o3, 14799701, 6
-
1
tz.transition 2041, 10, :o2, 59203675, 24
-
1
tz.transition 2042, 4, :o3, 14801885, 6
-
1
tz.transition 2042, 10, :o2, 59212411, 24
-
1
tz.transition 2043, 4, :o3, 14804069, 6
-
1
tz.transition 2043, 10, :o2, 59221147, 24
-
1
tz.transition 2044, 4, :o3, 14806253, 6
-
1
tz.transition 2044, 10, :o2, 59230051, 24
-
1
tz.transition 2045, 4, :o3, 14808437, 6
-
1
tz.transition 2045, 10, :o2, 59238787, 24
-
1
tz.transition 2046, 4, :o3, 14810621, 6
-
1
tz.transition 2046, 10, :o2, 59247523, 24
-
1
tz.transition 2047, 4, :o3, 14812847, 6
-
1
tz.transition 2047, 10, :o2, 59256259, 24
-
1
tz.transition 2048, 4, :o3, 14815031, 6
-
1
tz.transition 2048, 10, :o2, 59264995, 24
-
1
tz.transition 2049, 4, :o3, 14817215, 6
-
1
tz.transition 2049, 10, :o2, 59273899, 24
-
1
tz.transition 2050, 4, :o3, 14819399, 6
-
1
tz.transition 2050, 10, :o2, 59282635, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Monterrey
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Monterrey' do |tz|
-
1
tz.offset :o0, -24076, 0, :LMT
-
1
tz.offset :o1, -21600, 0, :CST
-
1
tz.offset :o2, -21600, 3600, :CDT
-
-
1
tz.transition 1922, 1, :o1, 9692223, 4
-
1
tz.transition 1988, 4, :o2, 576057600
-
1
tz.transition 1988, 10, :o1, 594198000
-
1
tz.transition 1996, 4, :o2, 828864000
-
1
tz.transition 1996, 10, :o1, 846399600
-
1
tz.transition 1997, 4, :o2, 860313600
-
1
tz.transition 1997, 10, :o1, 877849200
-
1
tz.transition 1998, 4, :o2, 891763200
-
1
tz.transition 1998, 10, :o1, 909298800
-
1
tz.transition 1999, 4, :o2, 923212800
-
1
tz.transition 1999, 10, :o1, 941353200
-
1
tz.transition 2000, 4, :o2, 954662400
-
1
tz.transition 2000, 10, :o1, 972802800
-
1
tz.transition 2001, 5, :o2, 989136000
-
1
tz.transition 2001, 9, :o1, 1001833200
-
1
tz.transition 2002, 4, :o2, 1018166400
-
1
tz.transition 2002, 10, :o1, 1035702000
-
1
tz.transition 2003, 4, :o2, 1049616000
-
1
tz.transition 2003, 10, :o1, 1067151600
-
1
tz.transition 2004, 4, :o2, 1081065600
-
1
tz.transition 2004, 10, :o1, 1099206000
-
1
tz.transition 2005, 4, :o2, 1112515200
-
1
tz.transition 2005, 10, :o1, 1130655600
-
1
tz.transition 2006, 4, :o2, 1143964800
-
1
tz.transition 2006, 10, :o1, 1162105200
-
1
tz.transition 2007, 4, :o2, 1175414400
-
1
tz.transition 2007, 10, :o1, 1193554800
-
1
tz.transition 2008, 4, :o2, 1207468800
-
1
tz.transition 2008, 10, :o1, 1225004400
-
1
tz.transition 2009, 4, :o2, 1238918400
-
1
tz.transition 2009, 10, :o1, 1256454000
-
1
tz.transition 2010, 4, :o2, 1270368000
-
1
tz.transition 2010, 10, :o1, 1288508400
-
1
tz.transition 2011, 4, :o2, 1301817600
-
1
tz.transition 2011, 10, :o1, 1319958000
-
1
tz.transition 2012, 4, :o2, 1333267200
-
1
tz.transition 2012, 10, :o1, 1351407600
-
1
tz.transition 2013, 4, :o2, 1365321600
-
1
tz.transition 2013, 10, :o1, 1382857200
-
1
tz.transition 2014, 4, :o2, 1396771200
-
1
tz.transition 2014, 10, :o1, 1414306800
-
1
tz.transition 2015, 4, :o2, 1428220800
-
1
tz.transition 2015, 10, :o1, 1445756400
-
1
tz.transition 2016, 4, :o2, 1459670400
-
1
tz.transition 2016, 10, :o1, 1477810800
-
1
tz.transition 2017, 4, :o2, 1491120000
-
1
tz.transition 2017, 10, :o1, 1509260400
-
1
tz.transition 2018, 4, :o2, 1522569600
-
1
tz.transition 2018, 10, :o1, 1540710000
-
1
tz.transition 2019, 4, :o2, 1554624000
-
1
tz.transition 2019, 10, :o1, 1572159600
-
1
tz.transition 2020, 4, :o2, 1586073600
-
1
tz.transition 2020, 10, :o1, 1603609200
-
1
tz.transition 2021, 4, :o2, 1617523200
-
1
tz.transition 2021, 10, :o1, 1635663600
-
1
tz.transition 2022, 4, :o2, 1648972800
-
1
tz.transition 2022, 10, :o1, 1667113200
-
1
tz.transition 2023, 4, :o2, 1680422400
-
1
tz.transition 2023, 10, :o1, 1698562800
-
1
tz.transition 2024, 4, :o2, 1712476800
-
1
tz.transition 2024, 10, :o1, 1730012400
-
1
tz.transition 2025, 4, :o2, 1743926400
-
1
tz.transition 2025, 10, :o1, 1761462000
-
1
tz.transition 2026, 4, :o2, 1775376000
-
1
tz.transition 2026, 10, :o1, 1792911600
-
1
tz.transition 2027, 4, :o2, 1806825600
-
1
tz.transition 2027, 10, :o1, 1824966000
-
1
tz.transition 2028, 4, :o2, 1838275200
-
1
tz.transition 2028, 10, :o1, 1856415600
-
1
tz.transition 2029, 4, :o2, 1869724800
-
1
tz.transition 2029, 10, :o1, 1887865200
-
1
tz.transition 2030, 4, :o2, 1901779200
-
1
tz.transition 2030, 10, :o1, 1919314800
-
1
tz.transition 2031, 4, :o2, 1933228800
-
1
tz.transition 2031, 10, :o1, 1950764400
-
1
tz.transition 2032, 4, :o2, 1964678400
-
1
tz.transition 2032, 10, :o1, 1982818800
-
1
tz.transition 2033, 4, :o2, 1996128000
-
1
tz.transition 2033, 10, :o1, 2014268400
-
1
tz.transition 2034, 4, :o2, 2027577600
-
1
tz.transition 2034, 10, :o1, 2045718000
-
1
tz.transition 2035, 4, :o2, 2059027200
-
1
tz.transition 2035, 10, :o1, 2077167600
-
1
tz.transition 2036, 4, :o2, 2091081600
-
1
tz.transition 2036, 10, :o1, 2108617200
-
1
tz.transition 2037, 4, :o2, 2122531200
-
1
tz.transition 2037, 10, :o1, 2140066800
-
1
tz.transition 2038, 4, :o2, 14793107, 6
-
1
tz.transition 2038, 10, :o1, 59177467, 24
-
1
tz.transition 2039, 4, :o2, 14795291, 6
-
1
tz.transition 2039, 10, :o1, 59186203, 24
-
1
tz.transition 2040, 4, :o2, 14797475, 6
-
1
tz.transition 2040, 10, :o1, 59194939, 24
-
1
tz.transition 2041, 4, :o2, 14799701, 6
-
1
tz.transition 2041, 10, :o1, 59203675, 24
-
1
tz.transition 2042, 4, :o2, 14801885, 6
-
1
tz.transition 2042, 10, :o1, 59212411, 24
-
1
tz.transition 2043, 4, :o2, 14804069, 6
-
1
tz.transition 2043, 10, :o1, 59221147, 24
-
1
tz.transition 2044, 4, :o2, 14806253, 6
-
1
tz.transition 2044, 10, :o1, 59230051, 24
-
1
tz.transition 2045, 4, :o2, 14808437, 6
-
1
tz.transition 2045, 10, :o1, 59238787, 24
-
1
tz.transition 2046, 4, :o2, 14810621, 6
-
1
tz.transition 2046, 10, :o1, 59247523, 24
-
1
tz.transition 2047, 4, :o2, 14812847, 6
-
1
tz.transition 2047, 10, :o1, 59256259, 24
-
1
tz.transition 2048, 4, :o2, 14815031, 6
-
1
tz.transition 2048, 10, :o1, 59264995, 24
-
1
tz.transition 2049, 4, :o2, 14817215, 6
-
1
tz.transition 2049, 10, :o1, 59273899, 24
-
1
tz.transition 2050, 4, :o2, 14819399, 6
-
1
tz.transition 2050, 10, :o1, 59282635, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Montevideo
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Montevideo' do |tz|
-
1
tz.offset :o0, -13484, 0, :LMT
-
1
tz.offset :o1, -13484, 0, :MMT
-
1
tz.offset :o2, -12600, 0, :UYT
-
1
tz.offset :o3, -12600, 1800, :UYHST
-
1
tz.offset :o4, -10800, 3600, :UYST
-
1
tz.offset :o5, -10800, 0, :UYT
-
1
tz.offset :o6, -10800, 1800, :UYHST
-
-
1
tz.transition 1898, 6, :o1, 52152522971, 21600
-
1
tz.transition 1920, 5, :o2, 52324826171, 21600
-
1
tz.transition 1923, 10, :o3, 116337343, 48
-
1
tz.transition 1924, 4, :o2, 19391013, 8
-
1
tz.transition 1924, 10, :o3, 116354863, 48
-
1
tz.transition 1925, 4, :o2, 19393933, 8
-
1
tz.transition 1925, 10, :o3, 116372383, 48
-
1
tz.transition 1926, 4, :o2, 19396853, 8
-
1
tz.transition 1933, 10, :o3, 116513983, 48
-
1
tz.transition 1934, 4, :o2, 19420229, 8
-
1
tz.transition 1934, 10, :o3, 116531455, 48
-
1
tz.transition 1935, 3, :o2, 19423141, 8
-
1
tz.transition 1935, 10, :o3, 116548927, 48
-
1
tz.transition 1936, 3, :o2, 19426053, 8
-
1
tz.transition 1936, 11, :o3, 116566735, 48
-
1
tz.transition 1937, 3, :o2, 19428965, 8
-
1
tz.transition 1937, 10, :o3, 116584207, 48
-
1
tz.transition 1938, 3, :o2, 19431877, 8
-
1
tz.transition 1938, 10, :o3, 116601679, 48
-
1
tz.transition 1939, 3, :o2, 19434789, 8
-
1
tz.transition 1939, 10, :o3, 116619151, 48
-
1
tz.transition 1940, 3, :o2, 19437757, 8
-
1
tz.transition 1940, 10, :o3, 116636623, 48
-
1
tz.transition 1941, 3, :o2, 19440669, 8
-
1
tz.transition 1941, 8, :o3, 116649967, 48
-
1
tz.transition 1942, 1, :o2, 19442885, 8
-
1
tz.transition 1942, 12, :o4, 116673967, 48
-
1
tz.transition 1943, 3, :o5, 29169571, 12
-
1
tz.transition 1959, 5, :o4, 19493701, 8
-
1
tz.transition 1959, 11, :o5, 29242651, 12
-
1
tz.transition 1960, 1, :o4, 19495605, 8
-
1
tz.transition 1960, 3, :o5, 29243995, 12
-
1
tz.transition 1965, 4, :o4, 19510837, 8
-
1
tz.transition 1965, 9, :o5, 29268355, 12
-
1
tz.transition 1966, 4, :o4, 19513749, 8
-
1
tz.transition 1966, 10, :o5, 29273155, 12
-
1
tz.transition 1967, 4, :o4, 19516661, 8
-
1
tz.transition 1967, 10, :o5, 29277535, 12
-
1
tz.transition 1968, 5, :o6, 19520029, 8
-
1
tz.transition 1968, 12, :o5, 117129245, 48
-
1
tz.transition 1969, 5, :o6, 19522949, 8
-
1
tz.transition 1969, 12, :o5, 117146765, 48
-
1
tz.transition 1970, 5, :o6, 12625200
-
1
tz.transition 1970, 12, :o5, 28953000
-
1
tz.transition 1972, 4, :o4, 72932400
-
1
tz.transition 1972, 8, :o5, 82692000
-
1
tz.transition 1974, 3, :o6, 132116400
-
1
tz.transition 1974, 12, :o4, 156911400
-
1
tz.transition 1976, 10, :o5, 212983200
-
1
tz.transition 1977, 12, :o4, 250052400
-
1
tz.transition 1978, 4, :o5, 260244000
-
1
tz.transition 1979, 10, :o4, 307594800
-
1
tz.transition 1980, 5, :o5, 325994400
-
1
tz.transition 1987, 12, :o4, 566449200
-
1
tz.transition 1988, 3, :o5, 574308000
-
1
tz.transition 1988, 12, :o4, 597812400
-
1
tz.transition 1989, 3, :o5, 605671200
-
1
tz.transition 1989, 10, :o4, 625633200
-
1
tz.transition 1990, 3, :o5, 636516000
-
1
tz.transition 1990, 10, :o4, 656478000
-
1
tz.transition 1991, 3, :o5, 667965600
-
1
tz.transition 1991, 10, :o4, 688532400
-
1
tz.transition 1992, 3, :o5, 699415200
-
1
tz.transition 1992, 10, :o4, 719377200
-
1
tz.transition 1993, 2, :o5, 730864800
-
1
tz.transition 2004, 9, :o4, 1095562800
-
1
tz.transition 2005, 3, :o5, 1111896000
-
1
tz.transition 2005, 10, :o4, 1128834000
-
1
tz.transition 2006, 3, :o5, 1142136000
-
1
tz.transition 2006, 10, :o4, 1159678800
-
1
tz.transition 2007, 3, :o5, 1173585600
-
1
tz.transition 2007, 10, :o4, 1191733200
-
1
tz.transition 2008, 3, :o5, 1205035200
-
1
tz.transition 2008, 10, :o4, 1223182800
-
1
tz.transition 2009, 3, :o5, 1236484800
-
1
tz.transition 2009, 10, :o4, 1254632400
-
1
tz.transition 2010, 3, :o5, 1268539200
-
1
tz.transition 2010, 10, :o4, 1286082000
-
1
tz.transition 2011, 3, :o5, 1299988800
-
1
tz.transition 2011, 10, :o4, 1317531600
-
1
tz.transition 2012, 3, :o5, 1331438400
-
1
tz.transition 2012, 10, :o4, 1349586000
-
1
tz.transition 2013, 3, :o5, 1362888000
-
1
tz.transition 2013, 10, :o4, 1381035600
-
1
tz.transition 2014, 3, :o5, 1394337600
-
1
tz.transition 2014, 10, :o4, 1412485200
-
1
tz.transition 2015, 3, :o5, 1425787200
-
1
tz.transition 2015, 10, :o4, 1443934800
-
1
tz.transition 2016, 3, :o5, 1457841600
-
1
tz.transition 2016, 10, :o4, 1475384400
-
1
tz.transition 2017, 3, :o5, 1489291200
-
1
tz.transition 2017, 10, :o4, 1506834000
-
1
tz.transition 2018, 3, :o5, 1520740800
-
1
tz.transition 2018, 10, :o4, 1538888400
-
1
tz.transition 2019, 3, :o5, 1552190400
-
1
tz.transition 2019, 10, :o4, 1570338000
-
1
tz.transition 2020, 3, :o5, 1583640000
-
1
tz.transition 2020, 10, :o4, 1601787600
-
1
tz.transition 2021, 3, :o5, 1615694400
-
1
tz.transition 2021, 10, :o4, 1633237200
-
1
tz.transition 2022, 3, :o5, 1647144000
-
1
tz.transition 2022, 10, :o4, 1664686800
-
1
tz.transition 2023, 3, :o5, 1678593600
-
1
tz.transition 2023, 10, :o4, 1696136400
-
1
tz.transition 2024, 3, :o5, 1710043200
-
1
tz.transition 2024, 10, :o4, 1728190800
-
1
tz.transition 2025, 3, :o5, 1741492800
-
1
tz.transition 2025, 10, :o4, 1759640400
-
1
tz.transition 2026, 3, :o5, 1772942400
-
1
tz.transition 2026, 10, :o4, 1791090000
-
1
tz.transition 2027, 3, :o5, 1804996800
-
1
tz.transition 2027, 10, :o4, 1822539600
-
1
tz.transition 2028, 3, :o5, 1836446400
-
1
tz.transition 2028, 10, :o4, 1853989200
-
1
tz.transition 2029, 3, :o5, 1867896000
-
1
tz.transition 2029, 10, :o4, 1886043600
-
1
tz.transition 2030, 3, :o5, 1899345600
-
1
tz.transition 2030, 10, :o4, 1917493200
-
1
tz.transition 2031, 3, :o5, 1930795200
-
1
tz.transition 2031, 10, :o4, 1948942800
-
1
tz.transition 2032, 3, :o5, 1962849600
-
1
tz.transition 2032, 10, :o4, 1980392400
-
1
tz.transition 2033, 3, :o5, 1994299200
-
1
tz.transition 2033, 10, :o4, 2011842000
-
1
tz.transition 2034, 3, :o5, 2025748800
-
1
tz.transition 2034, 10, :o4, 2043291600
-
1
tz.transition 2035, 3, :o5, 2057198400
-
1
tz.transition 2035, 10, :o4, 2075346000
-
1
tz.transition 2036, 3, :o5, 2088648000
-
1
tz.transition 2036, 10, :o4, 2106795600
-
1
tz.transition 2037, 3, :o5, 2120097600
-
1
tz.transition 2037, 10, :o4, 2138245200
-
1
tz.transition 2038, 3, :o5, 7396490, 3
-
1
tz.transition 2038, 10, :o4, 59176793, 24
-
1
tz.transition 2039, 3, :o5, 7397582, 3
-
1
tz.transition 2039, 10, :o4, 59185529, 24
-
1
tz.transition 2040, 3, :o5, 7398674, 3
-
1
tz.transition 2040, 10, :o4, 59194433, 24
-
1
tz.transition 2041, 3, :o5, 7399766, 3
-
1
tz.transition 2041, 10, :o4, 59203169, 24
-
1
tz.transition 2042, 3, :o5, 7400858, 3
-
1
tz.transition 2042, 10, :o4, 59211905, 24
-
1
tz.transition 2043, 3, :o5, 7401950, 3
-
1
tz.transition 2043, 10, :o4, 59220641, 24
-
1
tz.transition 2044, 3, :o5, 7403063, 3
-
1
tz.transition 2044, 10, :o4, 59229377, 24
-
1
tz.transition 2045, 3, :o5, 7404155, 3
-
1
tz.transition 2045, 10, :o4, 59238113, 24
-
1
tz.transition 2046, 3, :o5, 7405247, 3
-
1
tz.transition 2046, 10, :o4, 59247017, 24
-
1
tz.transition 2047, 3, :o5, 7406339, 3
-
1
tz.transition 2047, 10, :o4, 59255753, 24
-
1
tz.transition 2048, 3, :o5, 7407431, 3
-
1
tz.transition 2048, 10, :o4, 59264489, 24
-
1
tz.transition 2049, 3, :o5, 7408544, 3
-
1
tz.transition 2049, 10, :o4, 59273225, 24
-
1
tz.transition 2050, 3, :o5, 7409636, 3
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module New_York
-
1
include TimezoneDefinition
-
-
1
timezone 'America/New_York' do |tz|
-
1
tz.offset :o0, -17762, 0, :LMT
-
1
tz.offset :o1, -18000, 0, :EST
-
1
tz.offset :o2, -18000, 3600, :EDT
-
1
tz.offset :o3, -18000, 3600, :EWT
-
1
tz.offset :o4, -18000, 3600, :EPT
-
-
1
tz.transition 1883, 11, :o1, 57819197, 24
-
1
tz.transition 1918, 3, :o2, 58120411, 24
-
1
tz.transition 1918, 10, :o1, 9687575, 4
-
1
tz.transition 1919, 3, :o2, 58129147, 24
-
1
tz.transition 1919, 10, :o1, 9689031, 4
-
1
tz.transition 1920, 3, :o2, 58137883, 24
-
1
tz.transition 1920, 10, :o1, 9690515, 4
-
1
tz.transition 1921, 4, :o2, 58147291, 24
-
1
tz.transition 1921, 9, :o1, 9691831, 4
-
1
tz.transition 1922, 4, :o2, 58156195, 24
-
1
tz.transition 1922, 9, :o1, 9693287, 4
-
1
tz.transition 1923, 4, :o2, 58164931, 24
-
1
tz.transition 1923, 9, :o1, 9694771, 4
-
1
tz.transition 1924, 4, :o2, 58173667, 24
-
1
tz.transition 1924, 9, :o1, 9696227, 4
-
1
tz.transition 1925, 4, :o2, 58182403, 24
-
1
tz.transition 1925, 9, :o1, 9697683, 4
-
1
tz.transition 1926, 4, :o2, 58191139, 24
-
1
tz.transition 1926, 9, :o1, 9699139, 4
-
1
tz.transition 1927, 4, :o2, 58199875, 24
-
1
tz.transition 1927, 9, :o1, 9700595, 4
-
1
tz.transition 1928, 4, :o2, 58208779, 24
-
1
tz.transition 1928, 9, :o1, 9702079, 4
-
1
tz.transition 1929, 4, :o2, 58217515, 24
-
1
tz.transition 1929, 9, :o1, 9703535, 4
-
1
tz.transition 1930, 4, :o2, 58226251, 24
-
1
tz.transition 1930, 9, :o1, 9704991, 4
-
1
tz.transition 1931, 4, :o2, 58234987, 24
-
1
tz.transition 1931, 9, :o1, 9706447, 4
-
1
tz.transition 1932, 4, :o2, 58243723, 24
-
1
tz.transition 1932, 9, :o1, 9707903, 4
-
1
tz.transition 1933, 4, :o2, 58252627, 24
-
1
tz.transition 1933, 9, :o1, 9709359, 4
-
1
tz.transition 1934, 4, :o2, 58261363, 24
-
1
tz.transition 1934, 9, :o1, 9710843, 4
-
1
tz.transition 1935, 4, :o2, 58270099, 24
-
1
tz.transition 1935, 9, :o1, 9712299, 4
-
1
tz.transition 1936, 4, :o2, 58278835, 24
-
1
tz.transition 1936, 9, :o1, 9713755, 4
-
1
tz.transition 1937, 4, :o2, 58287571, 24
-
1
tz.transition 1937, 9, :o1, 9715211, 4
-
1
tz.transition 1938, 4, :o2, 58296307, 24
-
1
tz.transition 1938, 9, :o1, 9716667, 4
-
1
tz.transition 1939, 4, :o2, 58305211, 24
-
1
tz.transition 1939, 9, :o1, 9718123, 4
-
1
tz.transition 1940, 4, :o2, 58313947, 24
-
1
tz.transition 1940, 9, :o1, 9719607, 4
-
1
tz.transition 1941, 4, :o2, 58322683, 24
-
1
tz.transition 1941, 9, :o1, 9721063, 4
-
1
tz.transition 1942, 2, :o3, 58329595, 24
-
1
tz.transition 1945, 8, :o4, 58360379, 24
-
1
tz.transition 1945, 9, :o1, 9726915, 4
-
1
tz.transition 1946, 4, :o2, 58366531, 24
-
1
tz.transition 1946, 9, :o1, 9728371, 4
-
1
tz.transition 1947, 4, :o2, 58375267, 24
-
1
tz.transition 1947, 9, :o1, 9729827, 4
-
1
tz.transition 1948, 4, :o2, 58384003, 24
-
1
tz.transition 1948, 9, :o1, 9731283, 4
-
1
tz.transition 1949, 4, :o2, 58392739, 24
-
1
tz.transition 1949, 9, :o1, 9732739, 4
-
1
tz.transition 1950, 4, :o2, 58401643, 24
-
1
tz.transition 1950, 9, :o1, 9734195, 4
-
1
tz.transition 1951, 4, :o2, 58410379, 24
-
1
tz.transition 1951, 9, :o1, 9735679, 4
-
1
tz.transition 1952, 4, :o2, 58419115, 24
-
1
tz.transition 1952, 9, :o1, 9737135, 4
-
1
tz.transition 1953, 4, :o2, 58427851, 24
-
1
tz.transition 1953, 9, :o1, 9738591, 4
-
1
tz.transition 1954, 4, :o2, 58436587, 24
-
1
tz.transition 1954, 9, :o1, 9740047, 4
-
1
tz.transition 1955, 4, :o2, 58445323, 24
-
1
tz.transition 1955, 10, :o1, 9741643, 4
-
1
tz.transition 1956, 4, :o2, 58454227, 24
-
1
tz.transition 1956, 10, :o1, 9743099, 4
-
1
tz.transition 1957, 4, :o2, 58462963, 24
-
1
tz.transition 1957, 10, :o1, 9744555, 4
-
1
tz.transition 1958, 4, :o2, 58471699, 24
-
1
tz.transition 1958, 10, :o1, 9746011, 4
-
1
tz.transition 1959, 4, :o2, 58480435, 24
-
1
tz.transition 1959, 10, :o1, 9747467, 4
-
1
tz.transition 1960, 4, :o2, 58489171, 24
-
1
tz.transition 1960, 10, :o1, 9748951, 4
-
1
tz.transition 1961, 4, :o2, 58498075, 24
-
1
tz.transition 1961, 10, :o1, 9750407, 4
-
1
tz.transition 1962, 4, :o2, 58506811, 24
-
1
tz.transition 1962, 10, :o1, 9751863, 4
-
1
tz.transition 1963, 4, :o2, 58515547, 24
-
1
tz.transition 1963, 10, :o1, 9753319, 4
-
1
tz.transition 1964, 4, :o2, 58524283, 24
-
1
tz.transition 1964, 10, :o1, 9754775, 4
-
1
tz.transition 1965, 4, :o2, 58533019, 24
-
1
tz.transition 1965, 10, :o1, 9756259, 4
-
1
tz.transition 1966, 4, :o2, 58541755, 24
-
1
tz.transition 1966, 10, :o1, 9757715, 4
-
1
tz.transition 1967, 4, :o2, 58550659, 24
-
1
tz.transition 1967, 10, :o1, 9759171, 4
-
1
tz.transition 1968, 4, :o2, 58559395, 24
-
1
tz.transition 1968, 10, :o1, 9760627, 4
-
1
tz.transition 1969, 4, :o2, 58568131, 24
-
1
tz.transition 1969, 10, :o1, 9762083, 4
-
1
tz.transition 1970, 4, :o2, 9961200
-
1
tz.transition 1970, 10, :o1, 25682400
-
1
tz.transition 1971, 4, :o2, 41410800
-
1
tz.transition 1971, 10, :o1, 57736800
-
1
tz.transition 1972, 4, :o2, 73465200
-
1
tz.transition 1972, 10, :o1, 89186400
-
1
tz.transition 1973, 4, :o2, 104914800
-
1
tz.transition 1973, 10, :o1, 120636000
-
1
tz.transition 1974, 1, :o2, 126687600
-
1
tz.transition 1974, 10, :o1, 152085600
-
1
tz.transition 1975, 2, :o2, 162370800
-
1
tz.transition 1975, 10, :o1, 183535200
-
1
tz.transition 1976, 4, :o2, 199263600
-
1
tz.transition 1976, 10, :o1, 215589600
-
1
tz.transition 1977, 4, :o2, 230713200
-
1
tz.transition 1977, 10, :o1, 247039200
-
1
tz.transition 1978, 4, :o2, 262767600
-
1
tz.transition 1978, 10, :o1, 278488800
-
1
tz.transition 1979, 4, :o2, 294217200
-
1
tz.transition 1979, 10, :o1, 309938400
-
1
tz.transition 1980, 4, :o2, 325666800
-
1
tz.transition 1980, 10, :o1, 341388000
-
1
tz.transition 1981, 4, :o2, 357116400
-
1
tz.transition 1981, 10, :o1, 372837600
-
1
tz.transition 1982, 4, :o2, 388566000
-
1
tz.transition 1982, 10, :o1, 404892000
-
1
tz.transition 1983, 4, :o2, 420015600
-
1
tz.transition 1983, 10, :o1, 436341600
-
1
tz.transition 1984, 4, :o2, 452070000
-
1
tz.transition 1984, 10, :o1, 467791200
-
1
tz.transition 1985, 4, :o2, 483519600
-
1
tz.transition 1985, 10, :o1, 499240800
-
1
tz.transition 1986, 4, :o2, 514969200
-
1
tz.transition 1986, 10, :o1, 530690400
-
1
tz.transition 1987, 4, :o2, 544604400
-
1
tz.transition 1987, 10, :o1, 562140000
-
1
tz.transition 1988, 4, :o2, 576054000
-
1
tz.transition 1988, 10, :o1, 594194400
-
1
tz.transition 1989, 4, :o2, 607503600
-
1
tz.transition 1989, 10, :o1, 625644000
-
1
tz.transition 1990, 4, :o2, 638953200
-
1
tz.transition 1990, 10, :o1, 657093600
-
1
tz.transition 1991, 4, :o2, 671007600
-
1
tz.transition 1991, 10, :o1, 688543200
-
1
tz.transition 1992, 4, :o2, 702457200
-
1
tz.transition 1992, 10, :o1, 719992800
-
1
tz.transition 1993, 4, :o2, 733906800
-
1
tz.transition 1993, 10, :o1, 752047200
-
1
tz.transition 1994, 4, :o2, 765356400
-
1
tz.transition 1994, 10, :o1, 783496800
-
1
tz.transition 1995, 4, :o2, 796806000
-
1
tz.transition 1995, 10, :o1, 814946400
-
1
tz.transition 1996, 4, :o2, 828860400
-
1
tz.transition 1996, 10, :o1, 846396000
-
1
tz.transition 1997, 4, :o2, 860310000
-
1
tz.transition 1997, 10, :o1, 877845600
-
1
tz.transition 1998, 4, :o2, 891759600
-
1
tz.transition 1998, 10, :o1, 909295200
-
1
tz.transition 1999, 4, :o2, 923209200
-
1
tz.transition 1999, 10, :o1, 941349600
-
1
tz.transition 2000, 4, :o2, 954658800
-
1
tz.transition 2000, 10, :o1, 972799200
-
1
tz.transition 2001, 4, :o2, 986108400
-
1
tz.transition 2001, 10, :o1, 1004248800
-
1
tz.transition 2002, 4, :o2, 1018162800
-
1
tz.transition 2002, 10, :o1, 1035698400
-
1
tz.transition 2003, 4, :o2, 1049612400
-
1
tz.transition 2003, 10, :o1, 1067148000
-
1
tz.transition 2004, 4, :o2, 1081062000
-
1
tz.transition 2004, 10, :o1, 1099202400
-
1
tz.transition 2005, 4, :o2, 1112511600
-
1
tz.transition 2005, 10, :o1, 1130652000
-
1
tz.transition 2006, 4, :o2, 1143961200
-
1
tz.transition 2006, 10, :o1, 1162101600
-
1
tz.transition 2007, 3, :o2, 1173596400
-
1
tz.transition 2007, 11, :o1, 1194156000
-
1
tz.transition 2008, 3, :o2, 1205046000
-
1
tz.transition 2008, 11, :o1, 1225605600
-
1
tz.transition 2009, 3, :o2, 1236495600
-
1
tz.transition 2009, 11, :o1, 1257055200
-
1
tz.transition 2010, 3, :o2, 1268550000
-
1
tz.transition 2010, 11, :o1, 1289109600
-
1
tz.transition 2011, 3, :o2, 1299999600
-
1
tz.transition 2011, 11, :o1, 1320559200
-
1
tz.transition 2012, 3, :o2, 1331449200
-
1
tz.transition 2012, 11, :o1, 1352008800
-
1
tz.transition 2013, 3, :o2, 1362898800
-
1
tz.transition 2013, 11, :o1, 1383458400
-
1
tz.transition 2014, 3, :o2, 1394348400
-
1
tz.transition 2014, 11, :o1, 1414908000
-
1
tz.transition 2015, 3, :o2, 1425798000
-
1
tz.transition 2015, 11, :o1, 1446357600
-
1
tz.transition 2016, 3, :o2, 1457852400
-
1
tz.transition 2016, 11, :o1, 1478412000
-
1
tz.transition 2017, 3, :o2, 1489302000
-
1
tz.transition 2017, 11, :o1, 1509861600
-
1
tz.transition 2018, 3, :o2, 1520751600
-
1
tz.transition 2018, 11, :o1, 1541311200
-
1
tz.transition 2019, 3, :o2, 1552201200
-
1
tz.transition 2019, 11, :o1, 1572760800
-
1
tz.transition 2020, 3, :o2, 1583650800
-
1
tz.transition 2020, 11, :o1, 1604210400
-
1
tz.transition 2021, 3, :o2, 1615705200
-
1
tz.transition 2021, 11, :o1, 1636264800
-
1
tz.transition 2022, 3, :o2, 1647154800
-
1
tz.transition 2022, 11, :o1, 1667714400
-
1
tz.transition 2023, 3, :o2, 1678604400
-
1
tz.transition 2023, 11, :o1, 1699164000
-
1
tz.transition 2024, 3, :o2, 1710054000
-
1
tz.transition 2024, 11, :o1, 1730613600
-
1
tz.transition 2025, 3, :o2, 1741503600
-
1
tz.transition 2025, 11, :o1, 1762063200
-
1
tz.transition 2026, 3, :o2, 1772953200
-
1
tz.transition 2026, 11, :o1, 1793512800
-
1
tz.transition 2027, 3, :o2, 1805007600
-
1
tz.transition 2027, 11, :o1, 1825567200
-
1
tz.transition 2028, 3, :o2, 1836457200
-
1
tz.transition 2028, 11, :o1, 1857016800
-
1
tz.transition 2029, 3, :o2, 1867906800
-
1
tz.transition 2029, 11, :o1, 1888466400
-
1
tz.transition 2030, 3, :o2, 1899356400
-
1
tz.transition 2030, 11, :o1, 1919916000
-
1
tz.transition 2031, 3, :o2, 1930806000
-
1
tz.transition 2031, 11, :o1, 1951365600
-
1
tz.transition 2032, 3, :o2, 1962860400
-
1
tz.transition 2032, 11, :o1, 1983420000
-
1
tz.transition 2033, 3, :o2, 1994310000
-
1
tz.transition 2033, 11, :o1, 2014869600
-
1
tz.transition 2034, 3, :o2, 2025759600
-
1
tz.transition 2034, 11, :o1, 2046319200
-
1
tz.transition 2035, 3, :o2, 2057209200
-
1
tz.transition 2035, 11, :o1, 2077768800
-
1
tz.transition 2036, 3, :o2, 2088658800
-
1
tz.transition 2036, 11, :o1, 2109218400
-
1
tz.transition 2037, 3, :o2, 2120108400
-
1
tz.transition 2037, 11, :o1, 2140668000
-
1
tz.transition 2038, 3, :o2, 59171923, 24
-
1
tz.transition 2038, 11, :o1, 9862939, 4
-
1
tz.transition 2039, 3, :o2, 59180659, 24
-
1
tz.transition 2039, 11, :o1, 9864395, 4
-
1
tz.transition 2040, 3, :o2, 59189395, 24
-
1
tz.transition 2040, 11, :o1, 9865851, 4
-
1
tz.transition 2041, 3, :o2, 59198131, 24
-
1
tz.transition 2041, 11, :o1, 9867307, 4
-
1
tz.transition 2042, 3, :o2, 59206867, 24
-
1
tz.transition 2042, 11, :o1, 9868763, 4
-
1
tz.transition 2043, 3, :o2, 59215603, 24
-
1
tz.transition 2043, 11, :o1, 9870219, 4
-
1
tz.transition 2044, 3, :o2, 59224507, 24
-
1
tz.transition 2044, 11, :o1, 9871703, 4
-
1
tz.transition 2045, 3, :o2, 59233243, 24
-
1
tz.transition 2045, 11, :o1, 9873159, 4
-
1
tz.transition 2046, 3, :o2, 59241979, 24
-
1
tz.transition 2046, 11, :o1, 9874615, 4
-
1
tz.transition 2047, 3, :o2, 59250715, 24
-
1
tz.transition 2047, 11, :o1, 9876071, 4
-
1
tz.transition 2048, 3, :o2, 59259451, 24
-
1
tz.transition 2048, 11, :o1, 9877527, 4
-
1
tz.transition 2049, 3, :o2, 59268355, 24
-
1
tz.transition 2049, 11, :o1, 9879011, 4
-
1
tz.transition 2050, 3, :o2, 59277091, 24
-
1
tz.transition 2050, 11, :o1, 9880467, 4
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Phoenix
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Phoenix' do |tz|
-
1
tz.offset :o0, -26898, 0, :LMT
-
1
tz.offset :o1, -25200, 0, :MST
-
1
tz.offset :o2, -25200, 3600, :MDT
-
1
tz.offset :o3, -25200, 3600, :MWT
-
-
1
tz.transition 1883, 11, :o1, 57819199, 24
-
1
tz.transition 1918, 3, :o2, 19373471, 8
-
1
tz.transition 1918, 10, :o1, 14531363, 6
-
1
tz.transition 1919, 3, :o2, 19376383, 8
-
1
tz.transition 1919, 10, :o1, 14533547, 6
-
1
tz.transition 1942, 2, :o3, 19443199, 8
-
1
tz.transition 1944, 1, :o1, 3500770681, 1440
-
1
tz.transition 1944, 4, :o3, 3500901781, 1440
-
1
tz.transition 1944, 10, :o1, 3501165241, 1440
-
1
tz.transition 1967, 4, :o2, 19516887, 8
-
1
tz.transition 1967, 10, :o1, 14638757, 6
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Regina
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Regina' do |tz|
-
1
tz.offset :o0, -25116, 0, :LMT
-
1
tz.offset :o1, -25200, 0, :MST
-
1
tz.offset :o2, -25200, 3600, :MDT
-
1
tz.offset :o3, -25200, 3600, :MWT
-
1
tz.offset :o4, -25200, 3600, :MPT
-
1
tz.offset :o5, -21600, 0, :CST
-
-
1
tz.transition 1905, 9, :o1, 17403046493, 7200
-
1
tz.transition 1918, 4, :o2, 19373583, 8
-
1
tz.transition 1918, 10, :o1, 14531363, 6
-
1
tz.transition 1930, 5, :o2, 58226419, 24
-
1
tz.transition 1930, 10, :o1, 9705019, 4
-
1
tz.transition 1931, 5, :o2, 58235155, 24
-
1
tz.transition 1931, 10, :o1, 9706475, 4
-
1
tz.transition 1932, 5, :o2, 58243891, 24
-
1
tz.transition 1932, 10, :o1, 9707931, 4
-
1
tz.transition 1933, 5, :o2, 58252795, 24
-
1
tz.transition 1933, 10, :o1, 9709387, 4
-
1
tz.transition 1934, 5, :o2, 58261531, 24
-
1
tz.transition 1934, 10, :o1, 9710871, 4
-
1
tz.transition 1937, 4, :o2, 58287235, 24
-
1
tz.transition 1937, 10, :o1, 9715267, 4
-
1
tz.transition 1938, 4, :o2, 58295971, 24
-
1
tz.transition 1938, 10, :o1, 9716695, 4
-
1
tz.transition 1939, 4, :o2, 58304707, 24
-
1
tz.transition 1939, 10, :o1, 9718179, 4
-
1
tz.transition 1940, 4, :o2, 58313611, 24
-
1
tz.transition 1940, 10, :o1, 9719663, 4
-
1
tz.transition 1941, 4, :o2, 58322347, 24
-
1
tz.transition 1941, 10, :o1, 9721119, 4
-
1
tz.transition 1942, 2, :o3, 19443199, 8
-
1
tz.transition 1945, 8, :o4, 58360379, 24
-
1
tz.transition 1945, 9, :o1, 14590373, 6
-
1
tz.transition 1946, 4, :o2, 19455399, 8
-
1
tz.transition 1946, 10, :o1, 14592641, 6
-
1
tz.transition 1947, 4, :o2, 19458423, 8
-
1
tz.transition 1947, 9, :o1, 14594741, 6
-
1
tz.transition 1948, 4, :o2, 19461335, 8
-
1
tz.transition 1948, 9, :o1, 14596925, 6
-
1
tz.transition 1949, 4, :o2, 19464247, 8
-
1
tz.transition 1949, 9, :o1, 14599109, 6
-
1
tz.transition 1950, 4, :o2, 19467215, 8
-
1
tz.transition 1950, 9, :o1, 14601293, 6
-
1
tz.transition 1951, 4, :o2, 19470127, 8
-
1
tz.transition 1951, 9, :o1, 14603519, 6
-
1
tz.transition 1952, 4, :o2, 19473039, 8
-
1
tz.transition 1952, 9, :o1, 14605703, 6
-
1
tz.transition 1953, 4, :o2, 19475951, 8
-
1
tz.transition 1953, 9, :o1, 14607887, 6
-
1
tz.transition 1954, 4, :o2, 19478863, 8
-
1
tz.transition 1954, 9, :o1, 14610071, 6
-
1
tz.transition 1955, 4, :o2, 19481775, 8
-
1
tz.transition 1955, 9, :o1, 14612255, 6
-
1
tz.transition 1956, 4, :o2, 19484743, 8
-
1
tz.transition 1956, 9, :o1, 14614481, 6
-
1
tz.transition 1957, 4, :o2, 19487655, 8
-
1
tz.transition 1957, 9, :o1, 14616665, 6
-
1
tz.transition 1959, 4, :o2, 19493479, 8
-
1
tz.transition 1959, 10, :o1, 14621201, 6
-
1
tz.transition 1960, 4, :o5, 19496391, 8
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Santiago
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Santiago' do |tz|
-
1
tz.offset :o0, -16966, 0, :LMT
-
1
tz.offset :o1, -16966, 0, :SMT
-
1
tz.offset :o2, -18000, 0, :CLT
-
1
tz.offset :o3, -14400, 0, :CLT
-
1
tz.offset :o4, -18000, 3600, :CLST
-
1
tz.offset :o5, -14400, 3600, :CLST
-
-
1
tz.transition 1890, 1, :o1, 104171127683, 43200
-
1
tz.transition 1910, 1, :o2, 104486660483, 43200
-
1
tz.transition 1916, 7, :o1, 58105097, 24
-
1
tz.transition 1918, 9, :o3, 104623388483, 43200
-
1
tz.transition 1919, 7, :o1, 7266422, 3
-
1
tz.transition 1927, 9, :o4, 104765386883, 43200
-
1
tz.transition 1928, 4, :o2, 7276013, 3
-
1
tz.transition 1928, 9, :o4, 58211777, 24
-
1
tz.transition 1929, 4, :o2, 7277108, 3
-
1
tz.transition 1929, 9, :o4, 58220537, 24
-
1
tz.transition 1930, 4, :o2, 7278203, 3
-
1
tz.transition 1930, 9, :o4, 58229297, 24
-
1
tz.transition 1931, 4, :o2, 7279298, 3
-
1
tz.transition 1931, 9, :o4, 58238057, 24
-
1
tz.transition 1932, 4, :o2, 7280396, 3
-
1
tz.transition 1932, 9, :o4, 58246841, 24
-
1
tz.transition 1942, 6, :o2, 7291535, 3
-
1
tz.transition 1942, 8, :o4, 58333745, 24
-
1
tz.transition 1946, 9, :o2, 19456517, 8
-
1
tz.transition 1947, 5, :o3, 58375865, 24
-
1
tz.transition 1968, 11, :o5, 7320491, 3
-
1
tz.transition 1969, 3, :o3, 19522485, 8
-
1
tz.transition 1969, 11, :o5, 7321646, 3
-
1
tz.transition 1970, 3, :o3, 7527600
-
1
tz.transition 1970, 10, :o5, 24465600
-
1
tz.transition 1971, 3, :o3, 37767600
-
1
tz.transition 1971, 10, :o5, 55915200
-
1
tz.transition 1972, 3, :o3, 69217200
-
1
tz.transition 1972, 10, :o5, 87969600
-
1
tz.transition 1973, 3, :o3, 100666800
-
1
tz.transition 1973, 9, :o5, 118209600
-
1
tz.transition 1974, 3, :o3, 132116400
-
1
tz.transition 1974, 10, :o5, 150868800
-
1
tz.transition 1975, 3, :o3, 163566000
-
1
tz.transition 1975, 10, :o5, 182318400
-
1
tz.transition 1976, 3, :o3, 195620400
-
1
tz.transition 1976, 10, :o5, 213768000
-
1
tz.transition 1977, 3, :o3, 227070000
-
1
tz.transition 1977, 10, :o5, 245217600
-
1
tz.transition 1978, 3, :o3, 258519600
-
1
tz.transition 1978, 10, :o5, 277272000
-
1
tz.transition 1979, 3, :o3, 289969200
-
1
tz.transition 1979, 10, :o5, 308721600
-
1
tz.transition 1980, 3, :o3, 321418800
-
1
tz.transition 1980, 10, :o5, 340171200
-
1
tz.transition 1981, 3, :o3, 353473200
-
1
tz.transition 1981, 10, :o5, 371620800
-
1
tz.transition 1982, 3, :o3, 384922800
-
1
tz.transition 1982, 10, :o5, 403070400
-
1
tz.transition 1983, 3, :o3, 416372400
-
1
tz.transition 1983, 10, :o5, 434520000
-
1
tz.transition 1984, 3, :o3, 447822000
-
1
tz.transition 1984, 10, :o5, 466574400
-
1
tz.transition 1985, 3, :o3, 479271600
-
1
tz.transition 1985, 10, :o5, 498024000
-
1
tz.transition 1986, 3, :o3, 510721200
-
1
tz.transition 1986, 10, :o5, 529473600
-
1
tz.transition 1987, 4, :o3, 545194800
-
1
tz.transition 1987, 10, :o5, 560923200
-
1
tz.transition 1988, 3, :o3, 574225200
-
1
tz.transition 1988, 10, :o5, 591768000
-
1
tz.transition 1989, 3, :o3, 605674800
-
1
tz.transition 1989, 10, :o5, 624427200
-
1
tz.transition 1990, 3, :o3, 637729200
-
1
tz.transition 1990, 9, :o5, 653457600
-
1
tz.transition 1991, 3, :o3, 668574000
-
1
tz.transition 1991, 10, :o5, 687326400
-
1
tz.transition 1992, 3, :o3, 700628400
-
1
tz.transition 1992, 10, :o5, 718776000
-
1
tz.transition 1993, 3, :o3, 732078000
-
1
tz.transition 1993, 10, :o5, 750225600
-
1
tz.transition 1994, 3, :o3, 763527600
-
1
tz.transition 1994, 10, :o5, 781675200
-
1
tz.transition 1995, 3, :o3, 794977200
-
1
tz.transition 1995, 10, :o5, 813729600
-
1
tz.transition 1996, 3, :o3, 826426800
-
1
tz.transition 1996, 10, :o5, 845179200
-
1
tz.transition 1997, 3, :o3, 859690800
-
1
tz.transition 1997, 10, :o5, 876628800
-
1
tz.transition 1998, 3, :o3, 889930800
-
1
tz.transition 1998, 9, :o5, 906868800
-
1
tz.transition 1999, 4, :o3, 923194800
-
1
tz.transition 1999, 10, :o5, 939528000
-
1
tz.transition 2000, 3, :o3, 952830000
-
1
tz.transition 2000, 10, :o5, 971582400
-
1
tz.transition 2001, 3, :o3, 984279600
-
1
tz.transition 2001, 10, :o5, 1003032000
-
1
tz.transition 2002, 3, :o3, 1015729200
-
1
tz.transition 2002, 10, :o5, 1034481600
-
1
tz.transition 2003, 3, :o3, 1047178800
-
1
tz.transition 2003, 10, :o5, 1065931200
-
1
tz.transition 2004, 3, :o3, 1079233200
-
1
tz.transition 2004, 10, :o5, 1097380800
-
1
tz.transition 2005, 3, :o3, 1110682800
-
1
tz.transition 2005, 10, :o5, 1128830400
-
1
tz.transition 2006, 3, :o3, 1142132400
-
1
tz.transition 2006, 10, :o5, 1160884800
-
1
tz.transition 2007, 3, :o3, 1173582000
-
1
tz.transition 2007, 10, :o5, 1192334400
-
1
tz.transition 2008, 3, :o3, 1206846000
-
1
tz.transition 2008, 10, :o5, 1223784000
-
1
tz.transition 2009, 3, :o3, 1237086000
-
1
tz.transition 2009, 10, :o5, 1255233600
-
1
tz.transition 2010, 4, :o3, 1270350000
-
1
tz.transition 2010, 10, :o5, 1286683200
-
1
tz.transition 2011, 5, :o3, 1304823600
-
1
tz.transition 2011, 8, :o5, 1313899200
-
1
tz.transition 2012, 4, :o3, 1335668400
-
1
tz.transition 2012, 9, :o5, 1346558400
-
1
tz.transition 2013, 3, :o3, 1362884400
-
1
tz.transition 2013, 10, :o5, 1381636800
-
1
tz.transition 2014, 3, :o3, 1394334000
-
1
tz.transition 2014, 10, :o5, 1413086400
-
1
tz.transition 2015, 3, :o3, 1426388400
-
1
tz.transition 2015, 10, :o5, 1444536000
-
1
tz.transition 2016, 3, :o3, 1457838000
-
1
tz.transition 2016, 10, :o5, 1475985600
-
1
tz.transition 2017, 3, :o3, 1489287600
-
1
tz.transition 2017, 10, :o5, 1508040000
-
1
tz.transition 2018, 3, :o3, 1520737200
-
1
tz.transition 2018, 10, :o5, 1539489600
-
1
tz.transition 2019, 3, :o3, 1552186800
-
1
tz.transition 2019, 10, :o5, 1570939200
-
1
tz.transition 2020, 3, :o3, 1584241200
-
1
tz.transition 2020, 10, :o5, 1602388800
-
1
tz.transition 2021, 3, :o3, 1615690800
-
1
tz.transition 2021, 10, :o5, 1633838400
-
1
tz.transition 2022, 3, :o3, 1647140400
-
1
tz.transition 2022, 10, :o5, 1665288000
-
1
tz.transition 2023, 3, :o3, 1678590000
-
1
tz.transition 2023, 10, :o5, 1697342400
-
1
tz.transition 2024, 3, :o3, 1710039600
-
1
tz.transition 2024, 10, :o5, 1728792000
-
1
tz.transition 2025, 3, :o3, 1741489200
-
1
tz.transition 2025, 10, :o5, 1760241600
-
1
tz.transition 2026, 3, :o3, 1773543600
-
1
tz.transition 2026, 10, :o5, 1791691200
-
1
tz.transition 2027, 3, :o3, 1804993200
-
1
tz.transition 2027, 10, :o5, 1823140800
-
1
tz.transition 2028, 3, :o3, 1836442800
-
1
tz.transition 2028, 10, :o5, 1855195200
-
1
tz.transition 2029, 3, :o3, 1867892400
-
1
tz.transition 2029, 10, :o5, 1886644800
-
1
tz.transition 2030, 3, :o3, 1899342000
-
1
tz.transition 2030, 10, :o5, 1918094400
-
1
tz.transition 2031, 3, :o3, 1930791600
-
1
tz.transition 2031, 10, :o5, 1949544000
-
1
tz.transition 2032, 3, :o3, 1962846000
-
1
tz.transition 2032, 10, :o5, 1980993600
-
1
tz.transition 2033, 3, :o3, 1994295600
-
1
tz.transition 2033, 10, :o5, 2012443200
-
1
tz.transition 2034, 3, :o3, 2025745200
-
1
tz.transition 2034, 10, :o5, 2044497600
-
1
tz.transition 2035, 3, :o3, 2057194800
-
1
tz.transition 2035, 10, :o5, 2075947200
-
1
tz.transition 2036, 3, :o3, 2088644400
-
1
tz.transition 2036, 10, :o5, 2107396800
-
1
tz.transition 2037, 3, :o3, 2120698800
-
1
tz.transition 2037, 10, :o5, 2138846400
-
1
tz.transition 2038, 3, :o3, 19723973, 8
-
1
tz.transition 2038, 10, :o5, 7397120, 3
-
1
tz.transition 2039, 3, :o3, 19726885, 8
-
1
tz.transition 2039, 10, :o5, 7398212, 3
-
1
tz.transition 2040, 3, :o3, 19729797, 8
-
1
tz.transition 2040, 10, :o5, 7399325, 3
-
1
tz.transition 2041, 3, :o3, 19732709, 8
-
1
tz.transition 2041, 10, :o5, 7400417, 3
-
1
tz.transition 2042, 3, :o3, 19735621, 8
-
1
tz.transition 2042, 10, :o5, 7401509, 3
-
1
tz.transition 2043, 3, :o3, 19738589, 8
-
1
tz.transition 2043, 10, :o5, 7402601, 3
-
1
tz.transition 2044, 3, :o3, 19741501, 8
-
1
tz.transition 2044, 10, :o5, 7403693, 3
-
1
tz.transition 2045, 3, :o3, 19744413, 8
-
1
tz.transition 2045, 10, :o5, 7404806, 3
-
1
tz.transition 2046, 3, :o3, 19747325, 8
-
1
tz.transition 2046, 10, :o5, 7405898, 3
-
1
tz.transition 2047, 3, :o3, 19750237, 8
-
1
tz.transition 2047, 10, :o5, 7406990, 3
-
1
tz.transition 2048, 3, :o3, 19753205, 8
-
1
tz.transition 2048, 10, :o5, 7408082, 3
-
1
tz.transition 2049, 3, :o3, 19756117, 8
-
1
tz.transition 2049, 10, :o5, 7409174, 3
-
1
tz.transition 2050, 3, :o3, 19759029, 8
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Sao_Paulo
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Sao_Paulo' do |tz|
-
1
tz.offset :o0, -11188, 0, :LMT
-
1
tz.offset :o1, -10800, 0, :BRT
-
1
tz.offset :o2, -10800, 3600, :BRST
-
-
1
tz.transition 1914, 1, :o1, 52274886397, 21600
-
1
tz.transition 1931, 10, :o2, 29119417, 12
-
1
tz.transition 1932, 4, :o1, 29121583, 12
-
1
tz.transition 1932, 10, :o2, 19415869, 8
-
1
tz.transition 1933, 4, :o1, 29125963, 12
-
1
tz.transition 1949, 12, :o2, 19466013, 8
-
1
tz.transition 1950, 4, :o1, 19467101, 8
-
1
tz.transition 1950, 12, :o2, 19468933, 8
-
1
tz.transition 1951, 4, :o1, 29204851, 12
-
1
tz.transition 1951, 12, :o2, 19471853, 8
-
1
tz.transition 1952, 4, :o1, 29209243, 12
-
1
tz.transition 1952, 12, :o2, 19474781, 8
-
1
tz.transition 1953, 3, :o1, 29213251, 12
-
1
tz.transition 1963, 10, :o2, 19506605, 8
-
1
tz.transition 1964, 3, :o1, 29261467, 12
-
1
tz.transition 1965, 1, :o2, 19510333, 8
-
1
tz.transition 1965, 3, :o1, 29266207, 12
-
1
tz.transition 1965, 12, :o2, 19512765, 8
-
1
tz.transition 1966, 3, :o1, 29270227, 12
-
1
tz.transition 1966, 11, :o2, 19515445, 8
-
1
tz.transition 1967, 3, :o1, 29274607, 12
-
1
tz.transition 1967, 11, :o2, 19518365, 8
-
1
tz.transition 1968, 3, :o1, 29278999, 12
-
1
tz.transition 1985, 11, :o2, 499748400
-
1
tz.transition 1986, 3, :o1, 511236000
-
1
tz.transition 1986, 10, :o2, 530593200
-
1
tz.transition 1987, 2, :o1, 540266400
-
1
tz.transition 1987, 10, :o2, 562129200
-
1
tz.transition 1988, 2, :o1, 571197600
-
1
tz.transition 1988, 10, :o2, 592974000
-
1
tz.transition 1989, 1, :o1, 602042400
-
1
tz.transition 1989, 10, :o2, 624423600
-
1
tz.transition 1990, 2, :o1, 634701600
-
1
tz.transition 1990, 10, :o2, 656478000
-
1
tz.transition 1991, 2, :o1, 666756000
-
1
tz.transition 1991, 10, :o2, 687927600
-
1
tz.transition 1992, 2, :o1, 697600800
-
1
tz.transition 1992, 10, :o2, 719982000
-
1
tz.transition 1993, 1, :o1, 728445600
-
1
tz.transition 1993, 10, :o2, 750826800
-
1
tz.transition 1994, 2, :o1, 761709600
-
1
tz.transition 1994, 10, :o2, 782276400
-
1
tz.transition 1995, 2, :o1, 793159200
-
1
tz.transition 1995, 10, :o2, 813726000
-
1
tz.transition 1996, 2, :o1, 824004000
-
1
tz.transition 1996, 10, :o2, 844570800
-
1
tz.transition 1997, 2, :o1, 856058400
-
1
tz.transition 1997, 10, :o2, 876106800
-
1
tz.transition 1998, 3, :o1, 888717600
-
1
tz.transition 1998, 10, :o2, 908074800
-
1
tz.transition 1999, 2, :o1, 919562400
-
1
tz.transition 1999, 10, :o2, 938919600
-
1
tz.transition 2000, 2, :o1, 951616800
-
1
tz.transition 2000, 10, :o2, 970974000
-
1
tz.transition 2001, 2, :o1, 982461600
-
1
tz.transition 2001, 10, :o2, 1003028400
-
1
tz.transition 2002, 2, :o1, 1013911200
-
1
tz.transition 2002, 11, :o2, 1036292400
-
1
tz.transition 2003, 2, :o1, 1045360800
-
1
tz.transition 2003, 10, :o2, 1066532400
-
1
tz.transition 2004, 2, :o1, 1076810400
-
1
tz.transition 2004, 11, :o2, 1099364400
-
1
tz.transition 2005, 2, :o1, 1108864800
-
1
tz.transition 2005, 10, :o2, 1129431600
-
1
tz.transition 2006, 2, :o1, 1140314400
-
1
tz.transition 2006, 11, :o2, 1162695600
-
1
tz.transition 2007, 2, :o1, 1172368800
-
1
tz.transition 2007, 10, :o2, 1192330800
-
1
tz.transition 2008, 2, :o1, 1203213600
-
1
tz.transition 2008, 10, :o2, 1224385200
-
1
tz.transition 2009, 2, :o1, 1234663200
-
1
tz.transition 2009, 10, :o2, 1255834800
-
1
tz.transition 2010, 2, :o1, 1266717600
-
1
tz.transition 2010, 10, :o2, 1287284400
-
1
tz.transition 2011, 2, :o1, 1298167200
-
1
tz.transition 2011, 10, :o2, 1318734000
-
1
tz.transition 2012, 2, :o1, 1330221600
-
1
tz.transition 2012, 10, :o2, 1350788400
-
1
tz.transition 2013, 2, :o1, 1361066400
-
1
tz.transition 2013, 10, :o2, 1382238000
-
1
tz.transition 2014, 2, :o1, 1392516000
-
1
tz.transition 2014, 10, :o2, 1413687600
-
1
tz.transition 2015, 2, :o1, 1424570400
-
1
tz.transition 2015, 10, :o2, 1445137200
-
1
tz.transition 2016, 2, :o1, 1456020000
-
1
tz.transition 2016, 10, :o2, 1476586800
-
1
tz.transition 2017, 2, :o1, 1487469600
-
1
tz.transition 2017, 10, :o2, 1508036400
-
1
tz.transition 2018, 2, :o1, 1518919200
-
1
tz.transition 2018, 10, :o2, 1540090800
-
1
tz.transition 2019, 2, :o1, 1550368800
-
1
tz.transition 2019, 10, :o2, 1571540400
-
1
tz.transition 2020, 2, :o1, 1581818400
-
1
tz.transition 2020, 10, :o2, 1602990000
-
1
tz.transition 2021, 2, :o1, 1613872800
-
1
tz.transition 2021, 10, :o2, 1634439600
-
1
tz.transition 2022, 2, :o1, 1645322400
-
1
tz.transition 2022, 10, :o2, 1665889200
-
1
tz.transition 2023, 2, :o1, 1677376800
-
1
tz.transition 2023, 10, :o2, 1697338800
-
1
tz.transition 2024, 2, :o1, 1708221600
-
1
tz.transition 2024, 10, :o2, 1729393200
-
1
tz.transition 2025, 2, :o1, 1739671200
-
1
tz.transition 2025, 10, :o2, 1760842800
-
1
tz.transition 2026, 2, :o1, 1771725600
-
1
tz.transition 2026, 10, :o2, 1792292400
-
1
tz.transition 2027, 2, :o1, 1803175200
-
1
tz.transition 2027, 10, :o2, 1823742000
-
1
tz.transition 2028, 2, :o1, 1834624800
-
1
tz.transition 2028, 10, :o2, 1855191600
-
1
tz.transition 2029, 2, :o1, 1866074400
-
1
tz.transition 2029, 10, :o2, 1887246000
-
1
tz.transition 2030, 2, :o1, 1897524000
-
1
tz.transition 2030, 10, :o2, 1918695600
-
1
tz.transition 2031, 2, :o1, 1928973600
-
1
tz.transition 2031, 10, :o2, 1950145200
-
1
tz.transition 2032, 2, :o1, 1960423200
-
1
tz.transition 2032, 10, :o2, 1981594800
-
1
tz.transition 2033, 2, :o1, 1992477600
-
1
tz.transition 2033, 10, :o2, 2013044400
-
1
tz.transition 2034, 2, :o1, 2024532000
-
1
tz.transition 2034, 10, :o2, 2044494000
-
1
tz.transition 2035, 2, :o1, 2055376800
-
1
tz.transition 2035, 10, :o2, 2076548400
-
1
tz.transition 2036, 2, :o1, 2086826400
-
1
tz.transition 2036, 10, :o2, 2107998000
-
1
tz.transition 2037, 2, :o1, 2118880800
-
1
tz.transition 2037, 10, :o2, 2139447600
-
1
tz.transition 2038, 2, :o1, 29585707, 12
-
1
tz.transition 2038, 10, :o2, 19725709, 8
-
1
tz.transition 2039, 2, :o1, 29590075, 12
-
1
tz.transition 2039, 10, :o2, 19728621, 8
-
1
tz.transition 2040, 2, :o1, 29594443, 12
-
1
tz.transition 2040, 10, :o2, 19731589, 8
-
1
tz.transition 2041, 2, :o1, 29598811, 12
-
1
tz.transition 2041, 10, :o2, 19734501, 8
-
1
tz.transition 2042, 2, :o1, 29603179, 12
-
1
tz.transition 2042, 10, :o2, 19737413, 8
-
1
tz.transition 2043, 2, :o1, 29607547, 12
-
1
tz.transition 2043, 10, :o2, 19740325, 8
-
1
tz.transition 2044, 2, :o1, 29611999, 12
-
1
tz.transition 2044, 10, :o2, 19743237, 8
-
1
tz.transition 2045, 2, :o1, 29616367, 12
-
1
tz.transition 2045, 10, :o2, 19746149, 8
-
1
tz.transition 2046, 2, :o1, 29620735, 12
-
1
tz.transition 2046, 10, :o2, 19749117, 8
-
1
tz.transition 2047, 2, :o1, 29625103, 12
-
1
tz.transition 2047, 10, :o2, 19752029, 8
-
1
tz.transition 2048, 2, :o1, 29629471, 12
-
1
tz.transition 2048, 10, :o2, 19754941, 8
-
1
tz.transition 2049, 2, :o1, 29633923, 12
-
1
tz.transition 2049, 10, :o2, 19757853, 8
-
1
tz.transition 2050, 2, :o1, 29638291, 12
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module St_Johns
-
1
include TimezoneDefinition
-
-
1
timezone 'America/St_Johns' do |tz|
-
1
tz.offset :o0, -12652, 0, :LMT
-
1
tz.offset :o1, -12652, 0, :NST
-
1
tz.offset :o2, -12652, 3600, :NDT
-
1
tz.offset :o3, -12600, 0, :NST
-
1
tz.offset :o4, -12600, 3600, :NDT
-
1
tz.offset :o5, -12600, 3600, :NWT
-
1
tz.offset :o6, -12600, 3600, :NPT
-
1
tz.offset :o7, -12600, 7200, :NDDT
-
-
1
tz.transition 1884, 1, :o1, 52038215563, 21600
-
1
tz.transition 1917, 4, :o2, 52300657363, 21600
-
1
tz.transition 1917, 9, :o1, 52304155663, 21600
-
1
tz.transition 1918, 4, :o2, 52308670963, 21600
-
1
tz.transition 1918, 10, :o1, 52312903663, 21600
-
1
tz.transition 1919, 5, :o2, 52317027463, 21600
-
1
tz.transition 1919, 8, :o1, 52319164963, 21600
-
1
tz.transition 1920, 5, :o2, 52324868263, 21600
-
1
tz.transition 1920, 11, :o1, 52328798563, 21600
-
1
tz.transition 1921, 5, :o2, 52332730663, 21600
-
1
tz.transition 1921, 10, :o1, 52336660963, 21600
-
1
tz.transition 1922, 5, :o2, 52340744263, 21600
-
1
tz.transition 1922, 10, :o1, 52344523363, 21600
-
1
tz.transition 1923, 5, :o2, 52348606663, 21600
-
1
tz.transition 1923, 10, :o1, 52352385763, 21600
-
1
tz.transition 1924, 5, :o2, 52356469063, 21600
-
1
tz.transition 1924, 10, :o1, 52360248163, 21600
-
1
tz.transition 1925, 5, :o2, 52364331463, 21600
-
1
tz.transition 1925, 10, :o1, 52368110563, 21600
-
1
tz.transition 1926, 5, :o2, 52372193863, 21600
-
1
tz.transition 1926, 11, :o1, 52376124163, 21600
-
1
tz.transition 1927, 5, :o2, 52380056263, 21600
-
1
tz.transition 1927, 10, :o1, 52383986563, 21600
-
1
tz.transition 1928, 5, :o2, 52388069863, 21600
-
1
tz.transition 1928, 10, :o1, 52391848963, 21600
-
1
tz.transition 1929, 5, :o2, 52395932263, 21600
-
1
tz.transition 1929, 10, :o1, 52399711363, 21600
-
1
tz.transition 1930, 5, :o2, 52403794663, 21600
-
1
tz.transition 1930, 10, :o1, 52407573763, 21600
-
1
tz.transition 1931, 5, :o2, 52411657063, 21600
-
1
tz.transition 1931, 10, :o1, 52415436163, 21600
-
1
tz.transition 1932, 5, :o2, 52419519463, 21600
-
1
tz.transition 1932, 10, :o1, 52423449763, 21600
-
1
tz.transition 1933, 5, :o2, 52427533063, 21600
-
1
tz.transition 1933, 10, :o1, 52431312163, 21600
-
1
tz.transition 1934, 5, :o2, 52435395463, 21600
-
1
tz.transition 1934, 10, :o1, 52439174563, 21600
-
1
tz.transition 1935, 3, :o3, 52442459563, 21600
-
1
tz.transition 1935, 5, :o4, 116540573, 48
-
1
tz.transition 1935, 10, :o3, 38849657, 16
-
1
tz.transition 1936, 5, :o4, 116558383, 48
-
1
tz.transition 1936, 10, :o3, 116565437, 48
-
1
tz.transition 1937, 5, :o4, 116575855, 48
-
1
tz.transition 1937, 10, :o3, 116582909, 48
-
1
tz.transition 1938, 5, :o4, 116593327, 48
-
1
tz.transition 1938, 10, :o3, 116600381, 48
-
1
tz.transition 1939, 5, :o4, 116611135, 48
-
1
tz.transition 1939, 10, :o3, 116617853, 48
-
1
tz.transition 1940, 5, :o4, 116628607, 48
-
1
tz.transition 1940, 10, :o3, 116635661, 48
-
1
tz.transition 1941, 5, :o4, 116646079, 48
-
1
tz.transition 1941, 10, :o3, 116653133, 48
-
1
tz.transition 1942, 5, :o5, 116663551, 48
-
1
tz.transition 1945, 8, :o6, 58360379, 24
-
1
tz.transition 1945, 9, :o3, 38907659, 16
-
1
tz.transition 1946, 5, :o4, 116733731, 48
-
1
tz.transition 1946, 10, :o3, 38913595, 16
-
1
tz.transition 1947, 5, :o4, 116751203, 48
-
1
tz.transition 1947, 10, :o3, 38919419, 16
-
1
tz.transition 1948, 5, :o4, 116768675, 48
-
1
tz.transition 1948, 10, :o3, 38925243, 16
-
1
tz.transition 1949, 5, :o4, 116786147, 48
-
1
tz.transition 1949, 10, :o3, 38931067, 16
-
1
tz.transition 1950, 5, :o4, 116803955, 48
-
1
tz.transition 1950, 10, :o3, 38937003, 16
-
1
tz.transition 1951, 4, :o4, 116820755, 48
-
1
tz.transition 1951, 9, :o3, 38942715, 16
-
1
tz.transition 1952, 4, :o4, 116838227, 48
-
1
tz.transition 1952, 9, :o3, 38948539, 16
-
1
tz.transition 1953, 4, :o4, 116855699, 48
-
1
tz.transition 1953, 9, :o3, 38954363, 16
-
1
tz.transition 1954, 4, :o4, 116873171, 48
-
1
tz.transition 1954, 9, :o3, 38960187, 16
-
1
tz.transition 1955, 4, :o4, 116890643, 48
-
1
tz.transition 1955, 9, :o3, 38966011, 16
-
1
tz.transition 1956, 4, :o4, 116908451, 48
-
1
tz.transition 1956, 9, :o3, 38971947, 16
-
1
tz.transition 1957, 4, :o4, 116925923, 48
-
1
tz.transition 1957, 9, :o3, 38977771, 16
-
1
tz.transition 1958, 4, :o4, 116943395, 48
-
1
tz.transition 1958, 9, :o3, 38983595, 16
-
1
tz.transition 1959, 4, :o4, 116960867, 48
-
1
tz.transition 1959, 9, :o3, 38989419, 16
-
1
tz.transition 1960, 4, :o4, 116978339, 48
-
1
tz.transition 1960, 10, :o3, 38995803, 16
-
1
tz.transition 1961, 4, :o4, 116996147, 48
-
1
tz.transition 1961, 10, :o3, 39001627, 16
-
1
tz.transition 1962, 4, :o4, 117013619, 48
-
1
tz.transition 1962, 10, :o3, 39007451, 16
-
1
tz.transition 1963, 4, :o4, 117031091, 48
-
1
tz.transition 1963, 10, :o3, 39013275, 16
-
1
tz.transition 1964, 4, :o4, 117048563, 48
-
1
tz.transition 1964, 10, :o3, 39019099, 16
-
1
tz.transition 1965, 4, :o4, 117066035, 48
-
1
tz.transition 1965, 10, :o3, 39025035, 16
-
1
tz.transition 1966, 4, :o4, 117083507, 48
-
1
tz.transition 1966, 10, :o3, 39030859, 16
-
1
tz.transition 1967, 4, :o4, 117101315, 48
-
1
tz.transition 1967, 10, :o3, 39036683, 16
-
1
tz.transition 1968, 4, :o4, 117118787, 48
-
1
tz.transition 1968, 10, :o3, 39042507, 16
-
1
tz.transition 1969, 4, :o4, 117136259, 48
-
1
tz.transition 1969, 10, :o3, 39048331, 16
-
1
tz.transition 1970, 4, :o4, 9955800
-
1
tz.transition 1970, 10, :o3, 25677000
-
1
tz.transition 1971, 4, :o4, 41405400
-
1
tz.transition 1971, 10, :o3, 57731400
-
1
tz.transition 1972, 4, :o4, 73459800
-
1
tz.transition 1972, 10, :o3, 89181000
-
1
tz.transition 1973, 4, :o4, 104909400
-
1
tz.transition 1973, 10, :o3, 120630600
-
1
tz.transition 1974, 4, :o4, 136359000
-
1
tz.transition 1974, 10, :o3, 152080200
-
1
tz.transition 1975, 4, :o4, 167808600
-
1
tz.transition 1975, 10, :o3, 183529800
-
1
tz.transition 1976, 4, :o4, 199258200
-
1
tz.transition 1976, 10, :o3, 215584200
-
1
tz.transition 1977, 4, :o4, 230707800
-
1
tz.transition 1977, 10, :o3, 247033800
-
1
tz.transition 1978, 4, :o4, 262762200
-
1
tz.transition 1978, 10, :o3, 278483400
-
1
tz.transition 1979, 4, :o4, 294211800
-
1
tz.transition 1979, 10, :o3, 309933000
-
1
tz.transition 1980, 4, :o4, 325661400
-
1
tz.transition 1980, 10, :o3, 341382600
-
1
tz.transition 1981, 4, :o4, 357111000
-
1
tz.transition 1981, 10, :o3, 372832200
-
1
tz.transition 1982, 4, :o4, 388560600
-
1
tz.transition 1982, 10, :o3, 404886600
-
1
tz.transition 1983, 4, :o4, 420010200
-
1
tz.transition 1983, 10, :o3, 436336200
-
1
tz.transition 1984, 4, :o4, 452064600
-
1
tz.transition 1984, 10, :o3, 467785800
-
1
tz.transition 1985, 4, :o4, 483514200
-
1
tz.transition 1985, 10, :o3, 499235400
-
1
tz.transition 1986, 4, :o4, 514963800
-
1
tz.transition 1986, 10, :o3, 530685000
-
1
tz.transition 1987, 4, :o4, 544591860
-
1
tz.transition 1987, 10, :o3, 562127460
-
1
tz.transition 1988, 4, :o7, 576041460
-
1
tz.transition 1988, 10, :o3, 594178260
-
1
tz.transition 1989, 4, :o4, 607491060
-
1
tz.transition 1989, 10, :o3, 625631460
-
1
tz.transition 1990, 4, :o4, 638940660
-
1
tz.transition 1990, 10, :o3, 657081060
-
1
tz.transition 1991, 4, :o4, 670995060
-
1
tz.transition 1991, 10, :o3, 688530660
-
1
tz.transition 1992, 4, :o4, 702444660
-
1
tz.transition 1992, 10, :o3, 719980260
-
1
tz.transition 1993, 4, :o4, 733894260
-
1
tz.transition 1993, 10, :o3, 752034660
-
1
tz.transition 1994, 4, :o4, 765343860
-
1
tz.transition 1994, 10, :o3, 783484260
-
1
tz.transition 1995, 4, :o4, 796793460
-
1
tz.transition 1995, 10, :o3, 814933860
-
1
tz.transition 1996, 4, :o4, 828847860
-
1
tz.transition 1996, 10, :o3, 846383460
-
1
tz.transition 1997, 4, :o4, 860297460
-
1
tz.transition 1997, 10, :o3, 877833060
-
1
tz.transition 1998, 4, :o4, 891747060
-
1
tz.transition 1998, 10, :o3, 909282660
-
1
tz.transition 1999, 4, :o4, 923196660
-
1
tz.transition 1999, 10, :o3, 941337060
-
1
tz.transition 2000, 4, :o4, 954646260
-
1
tz.transition 2000, 10, :o3, 972786660
-
1
tz.transition 2001, 4, :o4, 986095860
-
1
tz.transition 2001, 10, :o3, 1004236260
-
1
tz.transition 2002, 4, :o4, 1018150260
-
1
tz.transition 2002, 10, :o3, 1035685860
-
1
tz.transition 2003, 4, :o4, 1049599860
-
1
tz.transition 2003, 10, :o3, 1067135460
-
1
tz.transition 2004, 4, :o4, 1081049460
-
1
tz.transition 2004, 10, :o3, 1099189860
-
1
tz.transition 2005, 4, :o4, 1112499060
-
1
tz.transition 2005, 10, :o3, 1130639460
-
1
tz.transition 2006, 4, :o4, 1143948660
-
1
tz.transition 2006, 10, :o3, 1162089060
-
1
tz.transition 2007, 3, :o4, 1173583860
-
1
tz.transition 2007, 11, :o3, 1194143460
-
1
tz.transition 2008, 3, :o4, 1205033460
-
1
tz.transition 2008, 11, :o3, 1225593060
-
1
tz.transition 2009, 3, :o4, 1236483060
-
1
tz.transition 2009, 11, :o3, 1257042660
-
1
tz.transition 2010, 3, :o4, 1268537460
-
1
tz.transition 2010, 11, :o3, 1289097060
-
1
tz.transition 2011, 3, :o4, 1299987060
-
1
tz.transition 2011, 11, :o3, 1320553800
-
1
tz.transition 2012, 3, :o4, 1331443800
-
1
tz.transition 2012, 11, :o3, 1352003400
-
1
tz.transition 2013, 3, :o4, 1362893400
-
1
tz.transition 2013, 11, :o3, 1383453000
-
1
tz.transition 2014, 3, :o4, 1394343000
-
1
tz.transition 2014, 11, :o3, 1414902600
-
1
tz.transition 2015, 3, :o4, 1425792600
-
1
tz.transition 2015, 11, :o3, 1446352200
-
1
tz.transition 2016, 3, :o4, 1457847000
-
1
tz.transition 2016, 11, :o3, 1478406600
-
1
tz.transition 2017, 3, :o4, 1489296600
-
1
tz.transition 2017, 11, :o3, 1509856200
-
1
tz.transition 2018, 3, :o4, 1520746200
-
1
tz.transition 2018, 11, :o3, 1541305800
-
1
tz.transition 2019, 3, :o4, 1552195800
-
1
tz.transition 2019, 11, :o3, 1572755400
-
1
tz.transition 2020, 3, :o4, 1583645400
-
1
tz.transition 2020, 11, :o3, 1604205000
-
1
tz.transition 2021, 3, :o4, 1615699800
-
1
tz.transition 2021, 11, :o3, 1636259400
-
1
tz.transition 2022, 3, :o4, 1647149400
-
1
tz.transition 2022, 11, :o3, 1667709000
-
1
tz.transition 2023, 3, :o4, 1678599000
-
1
tz.transition 2023, 11, :o3, 1699158600
-
1
tz.transition 2024, 3, :o4, 1710048600
-
1
tz.transition 2024, 11, :o3, 1730608200
-
1
tz.transition 2025, 3, :o4, 1741498200
-
1
tz.transition 2025, 11, :o3, 1762057800
-
1
tz.transition 2026, 3, :o4, 1772947800
-
1
tz.transition 2026, 11, :o3, 1793507400
-
1
tz.transition 2027, 3, :o4, 1805002200
-
1
tz.transition 2027, 11, :o3, 1825561800
-
1
tz.transition 2028, 3, :o4, 1836451800
-
1
tz.transition 2028, 11, :o3, 1857011400
-
1
tz.transition 2029, 3, :o4, 1867901400
-
1
tz.transition 2029, 11, :o3, 1888461000
-
1
tz.transition 2030, 3, :o4, 1899351000
-
1
tz.transition 2030, 11, :o3, 1919910600
-
1
tz.transition 2031, 3, :o4, 1930800600
-
1
tz.transition 2031, 11, :o3, 1951360200
-
1
tz.transition 2032, 3, :o4, 1962855000
-
1
tz.transition 2032, 11, :o3, 1983414600
-
1
tz.transition 2033, 3, :o4, 1994304600
-
1
tz.transition 2033, 11, :o3, 2014864200
-
1
tz.transition 2034, 3, :o4, 2025754200
-
1
tz.transition 2034, 11, :o3, 2046313800
-
1
tz.transition 2035, 3, :o4, 2057203800
-
1
tz.transition 2035, 11, :o3, 2077763400
-
1
tz.transition 2036, 3, :o4, 2088653400
-
1
tz.transition 2036, 11, :o3, 2109213000
-
1
tz.transition 2037, 3, :o4, 2120103000
-
1
tz.transition 2037, 11, :o3, 2140662600
-
1
tz.transition 2038, 3, :o4, 118343843, 48
-
1
tz.transition 2038, 11, :o3, 39451755, 16
-
1
tz.transition 2039, 3, :o4, 118361315, 48
-
1
tz.transition 2039, 11, :o3, 39457579, 16
-
1
tz.transition 2040, 3, :o4, 118378787, 48
-
1
tz.transition 2040, 11, :o3, 39463403, 16
-
1
tz.transition 2041, 3, :o4, 118396259, 48
-
1
tz.transition 2041, 11, :o3, 39469227, 16
-
1
tz.transition 2042, 3, :o4, 118413731, 48
-
1
tz.transition 2042, 11, :o3, 39475051, 16
-
1
tz.transition 2043, 3, :o4, 118431203, 48
-
1
tz.transition 2043, 11, :o3, 39480875, 16
-
1
tz.transition 2044, 3, :o4, 118449011, 48
-
1
tz.transition 2044, 11, :o3, 39486811, 16
-
1
tz.transition 2045, 3, :o4, 118466483, 48
-
1
tz.transition 2045, 11, :o3, 39492635, 16
-
1
tz.transition 2046, 3, :o4, 118483955, 48
-
1
tz.transition 2046, 11, :o3, 39498459, 16
-
1
tz.transition 2047, 3, :o4, 118501427, 48
-
1
tz.transition 2047, 11, :o3, 39504283, 16
-
1
tz.transition 2048, 3, :o4, 118518899, 48
-
1
tz.transition 2048, 11, :o3, 39510107, 16
-
1
tz.transition 2049, 3, :o4, 118536707, 48
-
1
tz.transition 2049, 11, :o3, 39516043, 16
-
1
tz.transition 2050, 3, :o4, 118554179, 48
-
1
tz.transition 2050, 11, :o3, 39521867, 16
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module America
-
1
module Tijuana
-
1
include TimezoneDefinition
-
-
1
timezone 'America/Tijuana' do |tz|
-
1
tz.offset :o0, -28084, 0, :LMT
-
1
tz.offset :o1, -25200, 0, :MST
-
1
tz.offset :o2, -28800, 0, :PST
-
1
tz.offset :o3, -28800, 3600, :PDT
-
1
tz.offset :o4, -28800, 3600, :PWT
-
1
tz.offset :o5, -28800, 3600, :PPT
-
-
1
tz.transition 1922, 1, :o1, 14538335, 6
-
1
tz.transition 1924, 1, :o2, 58170859, 24
-
1
tz.transition 1927, 6, :o1, 58201027, 24
-
1
tz.transition 1930, 11, :o2, 58231099, 24
-
1
tz.transition 1931, 4, :o3, 14558597, 6
-
1
tz.transition 1931, 9, :o2, 58238755, 24
-
1
tz.transition 1942, 4, :o4, 14582843, 6
-
1
tz.transition 1945, 8, :o5, 58360379, 24
-
1
tz.transition 1945, 11, :o2, 58362523, 24
-
1
tz.transition 1948, 4, :o3, 14595881, 6
-
1
tz.transition 1949, 1, :o2, 58390339, 24
-
1
tz.transition 1954, 4, :o3, 29218295, 12
-
1
tz.transition 1954, 9, :o2, 19480095, 8
-
1
tz.transition 1955, 4, :o3, 29222663, 12
-
1
tz.transition 1955, 9, :o2, 19483007, 8
-
1
tz.transition 1956, 4, :o3, 29227115, 12
-
1
tz.transition 1956, 9, :o2, 19485975, 8
-
1
tz.transition 1957, 4, :o3, 29231483, 12
-
1
tz.transition 1957, 9, :o2, 19488887, 8
-
1
tz.transition 1958, 4, :o3, 29235851, 12
-
1
tz.transition 1958, 9, :o2, 19491799, 8
-
1
tz.transition 1959, 4, :o3, 29240219, 12
-
1
tz.transition 1959, 9, :o2, 19494711, 8
-
1
tz.transition 1960, 4, :o3, 29244587, 12
-
1
tz.transition 1960, 9, :o2, 19497623, 8
-
1
tz.transition 1976, 4, :o3, 199274400
-
1
tz.transition 1976, 10, :o2, 215600400
-
1
tz.transition 1977, 4, :o3, 230724000
-
1
tz.transition 1977, 10, :o2, 247050000
-
1
tz.transition 1978, 4, :o3, 262778400
-
1
tz.transition 1978, 10, :o2, 278499600
-
1
tz.transition 1979, 4, :o3, 294228000
-
1
tz.transition 1979, 10, :o2, 309949200
-
1
tz.transition 1980, 4, :o3, 325677600
-
1
tz.transition 1980, 10, :o2, 341398800
-
1
tz.transition 1981, 4, :o3, 357127200
-
1
tz.transition 1981, 10, :o2, 372848400
-
1
tz.transition 1982, 4, :o3, 388576800
-
1
tz.transition 1982, 10, :o2, 404902800
-
1
tz.transition 1983, 4, :o3, 420026400
-
1
tz.transition 1983, 10, :o2, 436352400
-
1
tz.transition 1984, 4, :o3, 452080800
-
1
tz.transition 1984, 10, :o2, 467802000
-
1
tz.transition 1985, 4, :o3, 483530400
-
1
tz.transition 1985, 10, :o2, 499251600
-
1
tz.transition 1986, 4, :o3, 514980000
-
1
tz.transition 1986, 10, :o2, 530701200
-
1
tz.transition 1987, 4, :o3, 544615200
-
1
tz.transition 1987, 10, :o2, 562150800
-
1
tz.transition 1988, 4, :o3, 576064800
-
1
tz.transition 1988, 10, :o2, 594205200
-
1
tz.transition 1989, 4, :o3, 607514400
-
1
tz.transition 1989, 10, :o2, 625654800
-
1
tz.transition 1990, 4, :o3, 638964000
-
1
tz.transition 1990, 10, :o2, 657104400
-
1
tz.transition 1991, 4, :o3, 671018400
-
1
tz.transition 1991, 10, :o2, 688554000
-
1
tz.transition 1992, 4, :o3, 702468000
-
1
tz.transition 1992, 10, :o2, 720003600
-
1
tz.transition 1993, 4, :o3, 733917600
-
1
tz.transition 1993, 10, :o2, 752058000
-
1
tz.transition 1994, 4, :o3, 765367200
-
1
tz.transition 1994, 10, :o2, 783507600
-
1
tz.transition 1995, 4, :o3, 796816800
-
1
tz.transition 1995, 10, :o2, 814957200
-
1
tz.transition 1996, 4, :o3, 828871200
-
1
tz.transition 1996, 10, :o2, 846406800
-
1
tz.transition 1997, 4, :o3, 860320800
-
1
tz.transition 1997, 10, :o2, 877856400
-
1
tz.transition 1998, 4, :o3, 891770400
-
1
tz.transition 1998, 10, :o2, 909306000
-
1
tz.transition 1999, 4, :o3, 923220000
-
1
tz.transition 1999, 10, :o2, 941360400
-
1
tz.transition 2000, 4, :o3, 954669600
-
1
tz.transition 2000, 10, :o2, 972810000
-
1
tz.transition 2001, 4, :o3, 986119200
-
1
tz.transition 2001, 10, :o2, 1004259600
-
1
tz.transition 2002, 4, :o3, 1018173600
-
1
tz.transition 2002, 10, :o2, 1035709200
-
1
tz.transition 2003, 4, :o3, 1049623200
-
1
tz.transition 2003, 10, :o2, 1067158800
-
1
tz.transition 2004, 4, :o3, 1081072800
-
1
tz.transition 2004, 10, :o2, 1099213200
-
1
tz.transition 2005, 4, :o3, 1112522400
-
1
tz.transition 2005, 10, :o2, 1130662800
-
1
tz.transition 2006, 4, :o3, 1143972000
-
1
tz.transition 2006, 10, :o2, 1162112400
-
1
tz.transition 2007, 4, :o3, 1175421600
-
1
tz.transition 2007, 10, :o2, 1193562000
-
1
tz.transition 2008, 4, :o3, 1207476000
-
1
tz.transition 2008, 10, :o2, 1225011600
-
1
tz.transition 2009, 4, :o3, 1238925600
-
1
tz.transition 2009, 10, :o2, 1256461200
-
1
tz.transition 2010, 3, :o3, 1268560800
-
1
tz.transition 2010, 11, :o2, 1289120400
-
1
tz.transition 2011, 3, :o3, 1300010400
-
1
tz.transition 2011, 11, :o2, 1320570000
-
1
tz.transition 2012, 3, :o3, 1331460000
-
1
tz.transition 2012, 11, :o2, 1352019600
-
1
tz.transition 2013, 3, :o3, 1362909600
-
1
tz.transition 2013, 11, :o2, 1383469200
-
1
tz.transition 2014, 3, :o3, 1394359200
-
1
tz.transition 2014, 11, :o2, 1414918800
-
1
tz.transition 2015, 3, :o3, 1425808800
-
1
tz.transition 2015, 11, :o2, 1446368400
-
1
tz.transition 2016, 3, :o3, 1457863200
-
1
tz.transition 2016, 11, :o2, 1478422800
-
1
tz.transition 2017, 3, :o3, 1489312800
-
1
tz.transition 2017, 11, :o2, 1509872400
-
1
tz.transition 2018, 3, :o3, 1520762400
-
1
tz.transition 2018, 11, :o2, 1541322000
-
1
tz.transition 2019, 3, :o3, 1552212000
-
1
tz.transition 2019, 11, :o2, 1572771600
-
1
tz.transition 2020, 3, :o3, 1583661600
-
1
tz.transition 2020, 11, :o2, 1604221200
-
1
tz.transition 2021, 3, :o3, 1615716000
-
1
tz.transition 2021, 11, :o2, 1636275600
-
1
tz.transition 2022, 3, :o3, 1647165600
-
1
tz.transition 2022, 11, :o2, 1667725200
-
1
tz.transition 2023, 3, :o3, 1678615200
-
1
tz.transition 2023, 11, :o2, 1699174800
-
1
tz.transition 2024, 3, :o3, 1710064800
-
1
tz.transition 2024, 11, :o2, 1730624400
-
1
tz.transition 2025, 3, :o3, 1741514400
-
1
tz.transition 2025, 11, :o2, 1762074000
-
1
tz.transition 2026, 3, :o3, 1772964000
-
1
tz.transition 2026, 11, :o2, 1793523600
-
1
tz.transition 2027, 3, :o3, 1805018400
-
1
tz.transition 2027, 11, :o2, 1825578000
-
1
tz.transition 2028, 3, :o3, 1836468000
-
1
tz.transition 2028, 11, :o2, 1857027600
-
1
tz.transition 2029, 3, :o3, 1867917600
-
1
tz.transition 2029, 11, :o2, 1888477200
-
1
tz.transition 2030, 3, :o3, 1899367200
-
1
tz.transition 2030, 11, :o2, 1919926800
-
1
tz.transition 2031, 3, :o3, 1930816800
-
1
tz.transition 2031, 11, :o2, 1951376400
-
1
tz.transition 2032, 3, :o3, 1962871200
-
1
tz.transition 2032, 11, :o2, 1983430800
-
1
tz.transition 2033, 3, :o3, 1994320800
-
1
tz.transition 2033, 11, :o2, 2014880400
-
1
tz.transition 2034, 3, :o3, 2025770400
-
1
tz.transition 2034, 11, :o2, 2046330000
-
1
tz.transition 2035, 3, :o3, 2057220000
-
1
tz.transition 2035, 11, :o2, 2077779600
-
1
tz.transition 2036, 3, :o3, 2088669600
-
1
tz.transition 2036, 11, :o2, 2109229200
-
1
tz.transition 2037, 3, :o3, 2120119200
-
1
tz.transition 2037, 11, :o2, 2140678800
-
1
tz.transition 2038, 3, :o3, 29585963, 12
-
1
tz.transition 2038, 11, :o2, 19725879, 8
-
1
tz.transition 2039, 3, :o3, 29590331, 12
-
1
tz.transition 2039, 11, :o2, 19728791, 8
-
1
tz.transition 2040, 3, :o3, 29594699, 12
-
1
tz.transition 2040, 11, :o2, 19731703, 8
-
1
tz.transition 2041, 3, :o3, 29599067, 12
-
1
tz.transition 2041, 11, :o2, 19734615, 8
-
1
tz.transition 2042, 3, :o3, 29603435, 12
-
1
tz.transition 2042, 11, :o2, 19737527, 8
-
1
tz.transition 2043, 3, :o3, 29607803, 12
-
1
tz.transition 2043, 11, :o2, 19740439, 8
-
1
tz.transition 2044, 3, :o3, 29612255, 12
-
1
tz.transition 2044, 11, :o2, 19743407, 8
-
1
tz.transition 2045, 3, :o3, 29616623, 12
-
1
tz.transition 2045, 11, :o2, 19746319, 8
-
1
tz.transition 2046, 3, :o3, 29620991, 12
-
1
tz.transition 2046, 11, :o2, 19749231, 8
-
1
tz.transition 2047, 3, :o3, 29625359, 12
-
1
tz.transition 2047, 11, :o2, 19752143, 8
-
1
tz.transition 2048, 3, :o3, 29629727, 12
-
1
tz.transition 2048, 11, :o2, 19755055, 8
-
1
tz.transition 2049, 3, :o3, 29634179, 12
-
1
tz.transition 2049, 11, :o2, 19758023, 8
-
1
tz.transition 2050, 3, :o3, 29638547, 12
-
1
tz.transition 2050, 11, :o2, 19760935, 8
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Almaty
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Almaty' do |tz|
-
1
tz.offset :o0, 18468, 0, :LMT
-
1
tz.offset :o1, 18000, 0, :ALMT
-
1
tz.offset :o2, 21600, 0, :ALMT
-
1
tz.offset :o3, 21600, 3600, :ALMST
-
-
1
tz.transition 1924, 5, :o1, 1939125829, 800
-
1
tz.transition 1930, 6, :o2, 58227559, 24
-
1
tz.transition 1981, 3, :o3, 354909600
-
1
tz.transition 1981, 9, :o2, 370717200
-
1
tz.transition 1982, 3, :o3, 386445600
-
1
tz.transition 1982, 9, :o2, 402253200
-
1
tz.transition 1983, 3, :o3, 417981600
-
1
tz.transition 1983, 9, :o2, 433789200
-
1
tz.transition 1984, 3, :o3, 449604000
-
1
tz.transition 1984, 9, :o2, 465336000
-
1
tz.transition 1985, 3, :o3, 481060800
-
1
tz.transition 1985, 9, :o2, 496785600
-
1
tz.transition 1986, 3, :o3, 512510400
-
1
tz.transition 1986, 9, :o2, 528235200
-
1
tz.transition 1987, 3, :o3, 543960000
-
1
tz.transition 1987, 9, :o2, 559684800
-
1
tz.transition 1988, 3, :o3, 575409600
-
1
tz.transition 1988, 9, :o2, 591134400
-
1
tz.transition 1989, 3, :o3, 606859200
-
1
tz.transition 1989, 9, :o2, 622584000
-
1
tz.transition 1990, 3, :o3, 638308800
-
1
tz.transition 1990, 9, :o2, 654638400
-
1
tz.transition 1992, 3, :o3, 701802000
-
1
tz.transition 1992, 9, :o2, 717523200
-
1
tz.transition 1993, 3, :o3, 733262400
-
1
tz.transition 1993, 9, :o2, 748987200
-
1
tz.transition 1994, 3, :o3, 764712000
-
1
tz.transition 1994, 9, :o2, 780436800
-
1
tz.transition 1995, 3, :o3, 796161600
-
1
tz.transition 1995, 9, :o2, 811886400
-
1
tz.transition 1996, 3, :o3, 828216000
-
1
tz.transition 1996, 10, :o2, 846360000
-
1
tz.transition 1997, 3, :o3, 859665600
-
1
tz.transition 1997, 10, :o2, 877809600
-
1
tz.transition 1998, 3, :o3, 891115200
-
1
tz.transition 1998, 10, :o2, 909259200
-
1
tz.transition 1999, 3, :o3, 922564800
-
1
tz.transition 1999, 10, :o2, 941313600
-
1
tz.transition 2000, 3, :o3, 954014400
-
1
tz.transition 2000, 10, :o2, 972763200
-
1
tz.transition 2001, 3, :o3, 985464000
-
1
tz.transition 2001, 10, :o2, 1004212800
-
1
tz.transition 2002, 3, :o3, 1017518400
-
1
tz.transition 2002, 10, :o2, 1035662400
-
1
tz.transition 2003, 3, :o3, 1048968000
-
1
tz.transition 2003, 10, :o2, 1067112000
-
1
tz.transition 2004, 3, :o3, 1080417600
-
1
tz.transition 2004, 10, :o2, 1099166400
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Baghdad
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Baghdad' do |tz|
-
1
tz.offset :o0, 10660, 0, :LMT
-
1
tz.offset :o1, 10656, 0, :BMT
-
1
tz.offset :o2, 10800, 0, :AST
-
1
tz.offset :o3, 10800, 3600, :ADT
-
-
1
tz.transition 1889, 12, :o1, 10417111387, 4320
-
1
tz.transition 1917, 12, :o2, 726478313, 300
-
1
tz.transition 1982, 4, :o3, 389048400
-
1
tz.transition 1982, 9, :o2, 402264000
-
1
tz.transition 1983, 3, :o3, 417906000
-
1
tz.transition 1983, 9, :o2, 433800000
-
1
tz.transition 1984, 3, :o3, 449614800
-
1
tz.transition 1984, 9, :o2, 465422400
-
1
tz.transition 1985, 3, :o3, 481150800
-
1
tz.transition 1985, 9, :o2, 496792800
-
1
tz.transition 1986, 3, :o3, 512517600
-
1
tz.transition 1986, 9, :o2, 528242400
-
1
tz.transition 1987, 3, :o3, 543967200
-
1
tz.transition 1987, 9, :o2, 559692000
-
1
tz.transition 1988, 3, :o3, 575416800
-
1
tz.transition 1988, 9, :o2, 591141600
-
1
tz.transition 1989, 3, :o3, 606866400
-
1
tz.transition 1989, 9, :o2, 622591200
-
1
tz.transition 1990, 3, :o3, 638316000
-
1
tz.transition 1990, 9, :o2, 654645600
-
1
tz.transition 1991, 4, :o3, 670464000
-
1
tz.transition 1991, 10, :o2, 686275200
-
1
tz.transition 1992, 4, :o3, 702086400
-
1
tz.transition 1992, 10, :o2, 717897600
-
1
tz.transition 1993, 4, :o3, 733622400
-
1
tz.transition 1993, 10, :o2, 749433600
-
1
tz.transition 1994, 4, :o3, 765158400
-
1
tz.transition 1994, 10, :o2, 780969600
-
1
tz.transition 1995, 4, :o3, 796694400
-
1
tz.transition 1995, 10, :o2, 812505600
-
1
tz.transition 1996, 4, :o3, 828316800
-
1
tz.transition 1996, 10, :o2, 844128000
-
1
tz.transition 1997, 4, :o3, 859852800
-
1
tz.transition 1997, 10, :o2, 875664000
-
1
tz.transition 1998, 4, :o3, 891388800
-
1
tz.transition 1998, 10, :o2, 907200000
-
1
tz.transition 1999, 4, :o3, 922924800
-
1
tz.transition 1999, 10, :o2, 938736000
-
1
tz.transition 2000, 4, :o3, 954547200
-
1
tz.transition 2000, 10, :o2, 970358400
-
1
tz.transition 2001, 4, :o3, 986083200
-
1
tz.transition 2001, 10, :o2, 1001894400
-
1
tz.transition 2002, 4, :o3, 1017619200
-
1
tz.transition 2002, 10, :o2, 1033430400
-
1
tz.transition 2003, 4, :o3, 1049155200
-
1
tz.transition 2003, 10, :o2, 1064966400
-
1
tz.transition 2004, 4, :o3, 1080777600
-
1
tz.transition 2004, 10, :o2, 1096588800
-
1
tz.transition 2005, 4, :o3, 1112313600
-
1
tz.transition 2005, 10, :o2, 1128124800
-
1
tz.transition 2006, 4, :o3, 1143849600
-
1
tz.transition 2006, 10, :o2, 1159660800
-
1
tz.transition 2007, 4, :o3, 1175385600
-
1
tz.transition 2007, 10, :o2, 1191196800
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Baku
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Baku' do |tz|
-
1
tz.offset :o0, 11964, 0, :LMT
-
1
tz.offset :o1, 10800, 0, :BAKT
-
1
tz.offset :o2, 14400, 0, :BAKT
-
1
tz.offset :o3, 14400, 3600, :BAKST
-
1
tz.offset :o4, 10800, 3600, :BAKST
-
1
tz.offset :o5, 10800, 3600, :AZST
-
1
tz.offset :o6, 10800, 0, :AZT
-
1
tz.offset :o7, 14400, 0, :AZT
-
1
tz.offset :o8, 14400, 3600, :AZST
-
-
1
tz.transition 1924, 5, :o1, 17452133003, 7200
-
1
tz.transition 1957, 2, :o2, 19487187, 8
-
1
tz.transition 1981, 3, :o3, 354916800
-
1
tz.transition 1981, 9, :o2, 370724400
-
1
tz.transition 1982, 3, :o3, 386452800
-
1
tz.transition 1982, 9, :o2, 402260400
-
1
tz.transition 1983, 3, :o3, 417988800
-
1
tz.transition 1983, 9, :o2, 433796400
-
1
tz.transition 1984, 3, :o3, 449611200
-
1
tz.transition 1984, 9, :o2, 465343200
-
1
tz.transition 1985, 3, :o3, 481068000
-
1
tz.transition 1985, 9, :o2, 496792800
-
1
tz.transition 1986, 3, :o3, 512517600
-
1
tz.transition 1986, 9, :o2, 528242400
-
1
tz.transition 1987, 3, :o3, 543967200
-
1
tz.transition 1987, 9, :o2, 559692000
-
1
tz.transition 1988, 3, :o3, 575416800
-
1
tz.transition 1988, 9, :o2, 591141600
-
1
tz.transition 1989, 3, :o3, 606866400
-
1
tz.transition 1989, 9, :o2, 622591200
-
1
tz.transition 1990, 3, :o3, 638316000
-
1
tz.transition 1990, 9, :o2, 654645600
-
1
tz.transition 1991, 3, :o4, 670370400
-
1
tz.transition 1991, 8, :o5, 683496000
-
1
tz.transition 1991, 9, :o6, 686098800
-
1
tz.transition 1992, 3, :o5, 701812800
-
1
tz.transition 1992, 9, :o7, 717534000
-
1
tz.transition 1996, 3, :o8, 828234000
-
1
tz.transition 1996, 10, :o7, 846378000
-
1
tz.transition 1997, 3, :o8, 859680000
-
1
tz.transition 1997, 10, :o7, 877824000
-
1
tz.transition 1998, 3, :o8, 891129600
-
1
tz.transition 1998, 10, :o7, 909273600
-
1
tz.transition 1999, 3, :o8, 922579200
-
1
tz.transition 1999, 10, :o7, 941328000
-
1
tz.transition 2000, 3, :o8, 954028800
-
1
tz.transition 2000, 10, :o7, 972777600
-
1
tz.transition 2001, 3, :o8, 985478400
-
1
tz.transition 2001, 10, :o7, 1004227200
-
1
tz.transition 2002, 3, :o8, 1017532800
-
1
tz.transition 2002, 10, :o7, 1035676800
-
1
tz.transition 2003, 3, :o8, 1048982400
-
1
tz.transition 2003, 10, :o7, 1067126400
-
1
tz.transition 2004, 3, :o8, 1080432000
-
1
tz.transition 2004, 10, :o7, 1099180800
-
1
tz.transition 2005, 3, :o8, 1111881600
-
1
tz.transition 2005, 10, :o7, 1130630400
-
1
tz.transition 2006, 3, :o8, 1143331200
-
1
tz.transition 2006, 10, :o7, 1162080000
-
1
tz.transition 2007, 3, :o8, 1174780800
-
1
tz.transition 2007, 10, :o7, 1193529600
-
1
tz.transition 2008, 3, :o8, 1206835200
-
1
tz.transition 2008, 10, :o7, 1224979200
-
1
tz.transition 2009, 3, :o8, 1238284800
-
1
tz.transition 2009, 10, :o7, 1256428800
-
1
tz.transition 2010, 3, :o8, 1269734400
-
1
tz.transition 2010, 10, :o7, 1288483200
-
1
tz.transition 2011, 3, :o8, 1301184000
-
1
tz.transition 2011, 10, :o7, 1319932800
-
1
tz.transition 2012, 3, :o8, 1332633600
-
1
tz.transition 2012, 10, :o7, 1351382400
-
1
tz.transition 2013, 3, :o8, 1364688000
-
1
tz.transition 2013, 10, :o7, 1382832000
-
1
tz.transition 2014, 3, :o8, 1396137600
-
1
tz.transition 2014, 10, :o7, 1414281600
-
1
tz.transition 2015, 3, :o8, 1427587200
-
1
tz.transition 2015, 10, :o7, 1445731200
-
1
tz.transition 2016, 3, :o8, 1459036800
-
1
tz.transition 2016, 10, :o7, 1477785600
-
1
tz.transition 2017, 3, :o8, 1490486400
-
1
tz.transition 2017, 10, :o7, 1509235200
-
1
tz.transition 2018, 3, :o8, 1521936000
-
1
tz.transition 2018, 10, :o7, 1540684800
-
1
tz.transition 2019, 3, :o8, 1553990400
-
1
tz.transition 2019, 10, :o7, 1572134400
-
1
tz.transition 2020, 3, :o8, 1585440000
-
1
tz.transition 2020, 10, :o7, 1603584000
-
1
tz.transition 2021, 3, :o8, 1616889600
-
1
tz.transition 2021, 10, :o7, 1635638400
-
1
tz.transition 2022, 3, :o8, 1648339200
-
1
tz.transition 2022, 10, :o7, 1667088000
-
1
tz.transition 2023, 3, :o8, 1679788800
-
1
tz.transition 2023, 10, :o7, 1698537600
-
1
tz.transition 2024, 3, :o8, 1711843200
-
1
tz.transition 2024, 10, :o7, 1729987200
-
1
tz.transition 2025, 3, :o8, 1743292800
-
1
tz.transition 2025, 10, :o7, 1761436800
-
1
tz.transition 2026, 3, :o8, 1774742400
-
1
tz.transition 2026, 10, :o7, 1792886400
-
1
tz.transition 2027, 3, :o8, 1806192000
-
1
tz.transition 2027, 10, :o7, 1824940800
-
1
tz.transition 2028, 3, :o8, 1837641600
-
1
tz.transition 2028, 10, :o7, 1856390400
-
1
tz.transition 2029, 3, :o8, 1869091200
-
1
tz.transition 2029, 10, :o7, 1887840000
-
1
tz.transition 2030, 3, :o8, 1901145600
-
1
tz.transition 2030, 10, :o7, 1919289600
-
1
tz.transition 2031, 3, :o8, 1932595200
-
1
tz.transition 2031, 10, :o7, 1950739200
-
1
tz.transition 2032, 3, :o8, 1964044800
-
1
tz.transition 2032, 10, :o7, 1982793600
-
1
tz.transition 2033, 3, :o8, 1995494400
-
1
tz.transition 2033, 10, :o7, 2014243200
-
1
tz.transition 2034, 3, :o8, 2026944000
-
1
tz.transition 2034, 10, :o7, 2045692800
-
1
tz.transition 2035, 3, :o8, 2058393600
-
1
tz.transition 2035, 10, :o7, 2077142400
-
1
tz.transition 2036, 3, :o8, 2090448000
-
1
tz.transition 2036, 10, :o7, 2108592000
-
1
tz.transition 2037, 3, :o8, 2121897600
-
1
tz.transition 2037, 10, :o7, 2140041600
-
1
tz.transition 2038, 3, :o8, 4931021, 2
-
1
tz.transition 2038, 10, :o7, 4931455, 2
-
1
tz.transition 2039, 3, :o8, 4931749, 2
-
1
tz.transition 2039, 10, :o7, 4932183, 2
-
1
tz.transition 2040, 3, :o8, 4932477, 2
-
1
tz.transition 2040, 10, :o7, 4932911, 2
-
1
tz.transition 2041, 3, :o8, 4933219, 2
-
1
tz.transition 2041, 10, :o7, 4933639, 2
-
1
tz.transition 2042, 3, :o8, 4933947, 2
-
1
tz.transition 2042, 10, :o7, 4934367, 2
-
1
tz.transition 2043, 3, :o8, 4934675, 2
-
1
tz.transition 2043, 10, :o7, 4935095, 2
-
1
tz.transition 2044, 3, :o8, 4935403, 2
-
1
tz.transition 2044, 10, :o7, 4935837, 2
-
1
tz.transition 2045, 3, :o8, 4936131, 2
-
1
tz.transition 2045, 10, :o7, 4936565, 2
-
1
tz.transition 2046, 3, :o8, 4936859, 2
-
1
tz.transition 2046, 10, :o7, 4937293, 2
-
1
tz.transition 2047, 3, :o8, 4937601, 2
-
1
tz.transition 2047, 10, :o7, 4938021, 2
-
1
tz.transition 2048, 3, :o8, 4938329, 2
-
1
tz.transition 2048, 10, :o7, 4938749, 2
-
1
tz.transition 2049, 3, :o8, 4939057, 2
-
1
tz.transition 2049, 10, :o7, 4939491, 2
-
1
tz.transition 2050, 3, :o8, 4939785, 2
-
1
tz.transition 2050, 10, :o7, 4940219, 2
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Bangkok
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Bangkok' do |tz|
-
1
tz.offset :o0, 24124, 0, :LMT
-
1
tz.offset :o1, 24124, 0, :BMT
-
1
tz.offset :o2, 25200, 0, :ICT
-
-
1
tz.transition 1879, 12, :o1, 52006648769, 21600
-
1
tz.transition 1920, 3, :o2, 52324168769, 21600
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Chongqing
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Chongqing' do |tz|
-
1
tz.offset :o0, 25580, 0, :LMT
-
1
tz.offset :o1, 25200, 0, :LONT
-
1
tz.offset :o2, 28800, 0, :CST
-
1
tz.offset :o3, 28800, 3600, :CDT
-
-
1
tz.transition 1927, 12, :o1, 10477063601, 4320
-
1
tz.transition 1980, 4, :o2, 325962000
-
1
tz.transition 1986, 5, :o3, 515520000
-
1
tz.transition 1986, 9, :o2, 527007600
-
1
tz.transition 1987, 4, :o3, 545155200
-
1
tz.transition 1987, 9, :o2, 558457200
-
1
tz.transition 1988, 4, :o3, 576604800
-
1
tz.transition 1988, 9, :o2, 589906800
-
1
tz.transition 1989, 4, :o3, 608659200
-
1
tz.transition 1989, 9, :o2, 621961200
-
1
tz.transition 1990, 4, :o3, 640108800
-
1
tz.transition 1990, 9, :o2, 653410800
-
1
tz.transition 1991, 4, :o3, 671558400
-
1
tz.transition 1991, 9, :o2, 684860400
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Colombo
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Colombo' do |tz|
-
1
tz.offset :o0, 19164, 0, :LMT
-
1
tz.offset :o1, 19172, 0, :MMT
-
1
tz.offset :o2, 19800, 0, :IST
-
1
tz.offset :o3, 19800, 1800, :IHST
-
1
tz.offset :o4, 19800, 3600, :IST
-
1
tz.offset :o5, 23400, 0, :LKT
-
1
tz.offset :o6, 21600, 0, :LKT
-
-
1
tz.transition 1879, 12, :o1, 17335550003, 7200
-
1
tz.transition 1905, 12, :o2, 52211763607, 21600
-
1
tz.transition 1942, 1, :o3, 116657485, 48
-
1
tz.transition 1942, 8, :o4, 9722413, 4
-
1
tz.transition 1945, 10, :o2, 38907909, 16
-
1
tz.transition 1996, 5, :o5, 832962600
-
1
tz.transition 1996, 10, :o6, 846266400
-
1
tz.transition 2006, 4, :o2, 1145039400
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Dhaka
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Dhaka' do |tz|
-
1
tz.offset :o0, 21700, 0, :LMT
-
1
tz.offset :o1, 21200, 0, :HMT
-
1
tz.offset :o2, 23400, 0, :BURT
-
1
tz.offset :o3, 19800, 0, :IST
-
1
tz.offset :o4, 21600, 0, :DACT
-
1
tz.offset :o5, 21600, 0, :BDT
-
1
tz.offset :o6, 21600, 3600, :BDST
-
-
1
tz.transition 1889, 12, :o1, 2083422167, 864
-
1
tz.transition 1941, 9, :o2, 524937943, 216
-
1
tz.transition 1942, 5, :o3, 116663723, 48
-
1
tz.transition 1942, 8, :o2, 116668957, 48
-
1
tz.transition 1951, 9, :o4, 116828123, 48
-
1
tz.transition 1971, 3, :o5, 38772000
-
1
tz.transition 2009, 6, :o6, 1245430800
-
1
tz.transition 2009, 12, :o5, 1262278740
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Hong_Kong
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Hong_Kong' do |tz|
-
1
tz.offset :o0, 27396, 0, :LMT
-
1
tz.offset :o1, 28800, 0, :HKT
-
1
tz.offset :o2, 28800, 3600, :HKST
-
1
tz.offset :o3, 32400, 0, :JST
-
-
1
tz.transition 1904, 10, :o1, 5800279639, 2400
-
1
tz.transition 1941, 3, :o2, 38881365, 16
-
1
tz.transition 1941, 9, :o1, 116652829, 48
-
1
tz.transition 1941, 12, :o3, 14582119, 6
-
1
tz.transition 1945, 9, :o1, 19453705, 8
-
1
tz.transition 1946, 4, :o2, 38910885, 16
-
1
tz.transition 1946, 11, :o1, 116743453, 48
-
1
tz.transition 1947, 4, :o2, 38916613, 16
-
1
tz.transition 1947, 12, :o1, 116762365, 48
-
1
tz.transition 1948, 5, :o2, 38922773, 16
-
1
tz.transition 1948, 10, :o1, 116777053, 48
-
1
tz.transition 1949, 4, :o2, 38928149, 16
-
1
tz.transition 1949, 10, :o1, 116794525, 48
-
1
tz.transition 1950, 4, :o2, 38933973, 16
-
1
tz.transition 1950, 10, :o1, 116811997, 48
-
1
tz.transition 1951, 3, :o2, 38939797, 16
-
1
tz.transition 1951, 10, :o1, 116829469, 48
-
1
tz.transition 1952, 4, :o2, 38945733, 16
-
1
tz.transition 1952, 10, :o1, 116846893, 48
-
1
tz.transition 1953, 4, :o2, 38951557, 16
-
1
tz.transition 1953, 10, :o1, 116864749, 48
-
1
tz.transition 1954, 3, :o2, 38957157, 16
-
1
tz.transition 1954, 10, :o1, 116882221, 48
-
1
tz.transition 1955, 3, :o2, 38962981, 16
-
1
tz.transition 1955, 11, :o1, 116900029, 48
-
1
tz.transition 1956, 3, :o2, 38968805, 16
-
1
tz.transition 1956, 11, :o1, 116917501, 48
-
1
tz.transition 1957, 3, :o2, 38974741, 16
-
1
tz.transition 1957, 11, :o1, 116934973, 48
-
1
tz.transition 1958, 3, :o2, 38980565, 16
-
1
tz.transition 1958, 11, :o1, 116952445, 48
-
1
tz.transition 1959, 3, :o2, 38986389, 16
-
1
tz.transition 1959, 10, :o1, 116969917, 48
-
1
tz.transition 1960, 3, :o2, 38992213, 16
-
1
tz.transition 1960, 11, :o1, 116987725, 48
-
1
tz.transition 1961, 3, :o2, 38998037, 16
-
1
tz.transition 1961, 11, :o1, 117005197, 48
-
1
tz.transition 1962, 3, :o2, 39003861, 16
-
1
tz.transition 1962, 11, :o1, 117022669, 48
-
1
tz.transition 1963, 3, :o2, 39009797, 16
-
1
tz.transition 1963, 11, :o1, 117040141, 48
-
1
tz.transition 1964, 3, :o2, 39015621, 16
-
1
tz.transition 1964, 10, :o1, 117057613, 48
-
1
tz.transition 1965, 4, :o2, 39021893, 16
-
1
tz.transition 1965, 10, :o1, 117074413, 48
-
1
tz.transition 1966, 4, :o2, 39027717, 16
-
1
tz.transition 1966, 10, :o1, 117091885, 48
-
1
tz.transition 1967, 4, :o2, 39033541, 16
-
1
tz.transition 1967, 10, :o1, 117109693, 48
-
1
tz.transition 1968, 4, :o2, 39039477, 16
-
1
tz.transition 1968, 10, :o1, 117127165, 48
-
1
tz.transition 1969, 4, :o2, 39045301, 16
-
1
tz.transition 1969, 10, :o1, 117144637, 48
-
1
tz.transition 1970, 4, :o2, 9315000
-
1
tz.transition 1970, 10, :o1, 25036200
-
1
tz.transition 1971, 4, :o2, 40764600
-
1
tz.transition 1971, 10, :o1, 56485800
-
1
tz.transition 1972, 4, :o2, 72214200
-
1
tz.transition 1972, 10, :o1, 88540200
-
1
tz.transition 1973, 4, :o2, 104268600
-
1
tz.transition 1973, 10, :o1, 119989800
-
1
tz.transition 1973, 12, :o2, 126041400
-
1
tz.transition 1974, 10, :o1, 151439400
-
1
tz.transition 1975, 4, :o2, 167167800
-
1
tz.transition 1975, 10, :o1, 182889000
-
1
tz.transition 1976, 4, :o2, 198617400
-
1
tz.transition 1976, 10, :o1, 214338600
-
1
tz.transition 1979, 5, :o2, 295385400
-
1
tz.transition 1979, 10, :o1, 309292200
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Irkutsk
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Irkutsk' do |tz|
-
1
tz.offset :o0, 25040, 0, :LMT
-
1
tz.offset :o1, 25040, 0, :IMT
-
1
tz.offset :o2, 25200, 0, :IRKT
-
1
tz.offset :o3, 28800, 0, :IRKT
-
1
tz.offset :o4, 28800, 3600, :IRKST
-
1
tz.offset :o5, 25200, 3600, :IRKST
-
1
tz.offset :o6, 32400, 0, :IRKT
-
-
1
tz.transition 1879, 12, :o1, 2600332427, 1080
-
1
tz.transition 1920, 1, :o2, 2616136067, 1080
-
1
tz.transition 1930, 6, :o3, 58227557, 24
-
1
tz.transition 1981, 3, :o4, 354902400
-
1
tz.transition 1981, 9, :o3, 370710000
-
1
tz.transition 1982, 3, :o4, 386438400
-
1
tz.transition 1982, 9, :o3, 402246000
-
1
tz.transition 1983, 3, :o4, 417974400
-
1
tz.transition 1983, 9, :o3, 433782000
-
1
tz.transition 1984, 3, :o4, 449596800
-
1
tz.transition 1984, 9, :o3, 465328800
-
1
tz.transition 1985, 3, :o4, 481053600
-
1
tz.transition 1985, 9, :o3, 496778400
-
1
tz.transition 1986, 3, :o4, 512503200
-
1
tz.transition 1986, 9, :o3, 528228000
-
1
tz.transition 1987, 3, :o4, 543952800
-
1
tz.transition 1987, 9, :o3, 559677600
-
1
tz.transition 1988, 3, :o4, 575402400
-
1
tz.transition 1988, 9, :o3, 591127200
-
1
tz.transition 1989, 3, :o4, 606852000
-
1
tz.transition 1989, 9, :o3, 622576800
-
1
tz.transition 1990, 3, :o4, 638301600
-
1
tz.transition 1990, 9, :o3, 654631200
-
1
tz.transition 1991, 3, :o5, 670356000
-
1
tz.transition 1991, 9, :o2, 686084400
-
1
tz.transition 1992, 1, :o3, 695761200
-
1
tz.transition 1992, 3, :o4, 701794800
-
1
tz.transition 1992, 9, :o3, 717516000
-
1
tz.transition 1993, 3, :o4, 733255200
-
1
tz.transition 1993, 9, :o3, 748980000
-
1
tz.transition 1994, 3, :o4, 764704800
-
1
tz.transition 1994, 9, :o3, 780429600
-
1
tz.transition 1995, 3, :o4, 796154400
-
1
tz.transition 1995, 9, :o3, 811879200
-
1
tz.transition 1996, 3, :o4, 828208800
-
1
tz.transition 1996, 10, :o3, 846352800
-
1
tz.transition 1997, 3, :o4, 859658400
-
1
tz.transition 1997, 10, :o3, 877802400
-
1
tz.transition 1998, 3, :o4, 891108000
-
1
tz.transition 1998, 10, :o3, 909252000
-
1
tz.transition 1999, 3, :o4, 922557600
-
1
tz.transition 1999, 10, :o3, 941306400
-
1
tz.transition 2000, 3, :o4, 954007200
-
1
tz.transition 2000, 10, :o3, 972756000
-
1
tz.transition 2001, 3, :o4, 985456800
-
1
tz.transition 2001, 10, :o3, 1004205600
-
1
tz.transition 2002, 3, :o4, 1017511200
-
1
tz.transition 2002, 10, :o3, 1035655200
-
1
tz.transition 2003, 3, :o4, 1048960800
-
1
tz.transition 2003, 10, :o3, 1067104800
-
1
tz.transition 2004, 3, :o4, 1080410400
-
1
tz.transition 2004, 10, :o3, 1099159200
-
1
tz.transition 2005, 3, :o4, 1111860000
-
1
tz.transition 2005, 10, :o3, 1130608800
-
1
tz.transition 2006, 3, :o4, 1143309600
-
1
tz.transition 2006, 10, :o3, 1162058400
-
1
tz.transition 2007, 3, :o4, 1174759200
-
1
tz.transition 2007, 10, :o3, 1193508000
-
1
tz.transition 2008, 3, :o4, 1206813600
-
1
tz.transition 2008, 10, :o3, 1224957600
-
1
tz.transition 2009, 3, :o4, 1238263200
-
1
tz.transition 2009, 10, :o3, 1256407200
-
1
tz.transition 2010, 3, :o4, 1269712800
-
1
tz.transition 2010, 10, :o3, 1288461600
-
1
tz.transition 2011, 3, :o6, 1301162400
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Jakarta
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Jakarta' do |tz|
-
1
tz.offset :o0, 25632, 0, :LMT
-
1
tz.offset :o1, 25632, 0, :JMT
-
1
tz.offset :o2, 26400, 0, :JAVT
-
1
tz.offset :o3, 27000, 0, :WIT
-
1
tz.offset :o4, 32400, 0, :JST
-
1
tz.offset :o5, 28800, 0, :WIT
-
1
tz.offset :o6, 25200, 0, :WIT
-
-
1
tz.transition 1867, 8, :o1, 720956461, 300
-
1
tz.transition 1923, 12, :o2, 87256267, 36
-
1
tz.transition 1932, 10, :o3, 87372439, 36
-
1
tz.transition 1942, 3, :o4, 38887059, 16
-
1
tz.transition 1945, 9, :o3, 19453769, 8
-
1
tz.transition 1948, 4, :o5, 38922755, 16
-
1
tz.transition 1950, 4, :o3, 14600413, 6
-
1
tz.transition 1963, 12, :o6, 39014323, 16
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Jerusalem
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Jerusalem' do |tz|
-
1
tz.offset :o0, 8456, 0, :LMT
-
1
tz.offset :o1, 8440, 0, :JMT
-
1
tz.offset :o2, 7200, 0, :IST
-
1
tz.offset :o3, 7200, 3600, :IDT
-
1
tz.offset :o4, 7200, 7200, :IDDT
-
-
1
tz.transition 1879, 12, :o1, 26003326343, 10800
-
1
tz.transition 1917, 12, :o2, 5230643909, 2160
-
1
tz.transition 1940, 5, :o3, 29157377, 12
-
1
tz.transition 1942, 10, :o2, 19445315, 8
-
1
tz.transition 1943, 4, :o3, 4861631, 2
-
1
tz.transition 1943, 10, :o2, 19448235, 8
-
1
tz.transition 1944, 3, :o3, 29174177, 12
-
1
tz.transition 1944, 10, :o2, 19451163, 8
-
1
tz.transition 1945, 4, :o3, 29178737, 12
-
1
tz.transition 1945, 10, :o2, 58362251, 24
-
1
tz.transition 1946, 4, :o3, 4863853, 2
-
1
tz.transition 1946, 10, :o2, 19457003, 8
-
1
tz.transition 1948, 5, :o4, 29192333, 12
-
1
tz.transition 1948, 8, :o3, 7298386, 3
-
1
tz.transition 1948, 10, :o2, 58388555, 24
-
1
tz.transition 1949, 4, :o3, 29196449, 12
-
1
tz.transition 1949, 10, :o2, 58397315, 24
-
1
tz.transition 1950, 4, :o3, 29200649, 12
-
1
tz.transition 1950, 9, :o2, 4867079, 2
-
1
tz.transition 1951, 3, :o3, 29204849, 12
-
1
tz.transition 1951, 11, :o2, 4867923, 2
-
1
tz.transition 1952, 4, :o3, 4868245, 2
-
1
tz.transition 1952, 10, :o2, 4868609, 2
-
1
tz.transition 1953, 4, :o3, 4868959, 2
-
1
tz.transition 1953, 9, :o2, 4869267, 2
-
1
tz.transition 1954, 6, :o3, 29218877, 12
-
1
tz.transition 1954, 9, :o2, 19479979, 8
-
1
tz.transition 1955, 6, :o3, 4870539, 2
-
1
tz.transition 1955, 9, :o2, 19482891, 8
-
1
tz.transition 1956, 6, :o3, 29227529, 12
-
1
tz.transition 1956, 9, :o2, 4871493, 2
-
1
tz.transition 1957, 4, :o3, 4871915, 2
-
1
tz.transition 1957, 9, :o2, 19488827, 8
-
1
tz.transition 1974, 7, :o3, 142380000
-
1
tz.transition 1974, 10, :o2, 150843600
-
1
tz.transition 1975, 4, :o3, 167176800
-
1
tz.transition 1975, 8, :o2, 178664400
-
1
tz.transition 1985, 4, :o3, 482277600
-
1
tz.transition 1985, 9, :o2, 495579600
-
1
tz.transition 1986, 5, :o3, 516751200
-
1
tz.transition 1986, 9, :o2, 526424400
-
1
tz.transition 1987, 4, :o3, 545436000
-
1
tz.transition 1987, 9, :o2, 558478800
-
1
tz.transition 1988, 4, :o3, 576540000
-
1
tz.transition 1988, 9, :o2, 589237200
-
1
tz.transition 1989, 4, :o3, 609890400
-
1
tz.transition 1989, 9, :o2, 620773200
-
1
tz.transition 1990, 3, :o3, 638316000
-
1
tz.transition 1990, 8, :o2, 651618000
-
1
tz.transition 1991, 3, :o3, 669765600
-
1
tz.transition 1991, 8, :o2, 683672400
-
1
tz.transition 1992, 3, :o3, 701820000
-
1
tz.transition 1992, 9, :o2, 715726800
-
1
tz.transition 1993, 4, :o3, 733701600
-
1
tz.transition 1993, 9, :o2, 747176400
-
1
tz.transition 1994, 3, :o3, 765151200
-
1
tz.transition 1994, 8, :o2, 778021200
-
1
tz.transition 1995, 3, :o3, 796600800
-
1
tz.transition 1995, 9, :o2, 810075600
-
1
tz.transition 1996, 3, :o3, 826840800
-
1
tz.transition 1996, 9, :o2, 842821200
-
1
tz.transition 1997, 3, :o3, 858895200
-
1
tz.transition 1997, 9, :o2, 874184400
-
1
tz.transition 1998, 3, :o3, 890344800
-
1
tz.transition 1998, 9, :o2, 905029200
-
1
tz.transition 1999, 4, :o3, 923011200
-
1
tz.transition 1999, 9, :o2, 936313200
-
1
tz.transition 2000, 4, :o3, 955670400
-
1
tz.transition 2000, 10, :o2, 970783200
-
1
tz.transition 2001, 4, :o3, 986770800
-
1
tz.transition 2001, 9, :o2, 1001282400
-
1
tz.transition 2002, 3, :o3, 1017356400
-
1
tz.transition 2002, 10, :o2, 1033941600
-
1
tz.transition 2003, 3, :o3, 1048806000
-
1
tz.transition 2003, 10, :o2, 1065132000
-
1
tz.transition 2004, 4, :o3, 1081292400
-
1
tz.transition 2004, 9, :o2, 1095804000
-
1
tz.transition 2005, 4, :o3, 1112313600
-
1
tz.transition 2005, 10, :o2, 1128812400
-
1
tz.transition 2006, 3, :o3, 1143763200
-
1
tz.transition 2006, 9, :o2, 1159657200
-
1
tz.transition 2007, 3, :o3, 1175212800
-
1
tz.transition 2007, 9, :o2, 1189897200
-
1
tz.transition 2008, 3, :o3, 1206662400
-
1
tz.transition 2008, 10, :o2, 1223161200
-
1
tz.transition 2009, 3, :o3, 1238112000
-
1
tz.transition 2009, 9, :o2, 1254006000
-
1
tz.transition 2010, 3, :o3, 1269561600
-
1
tz.transition 2010, 9, :o2, 1284246000
-
1
tz.transition 2011, 4, :o3, 1301616000
-
1
tz.transition 2011, 10, :o2, 1317510000
-
1
tz.transition 2012, 3, :o3, 1333065600
-
1
tz.transition 2012, 9, :o2, 1348354800
-
1
tz.transition 2013, 3, :o3, 1364515200
-
1
tz.transition 2013, 10, :o2, 1381014000
-
1
tz.transition 2014, 3, :o3, 1395964800
-
1
tz.transition 2014, 10, :o2, 1412463600
-
1
tz.transition 2015, 3, :o3, 1427414400
-
1
tz.transition 2015, 10, :o2, 1443913200
-
1
tz.transition 2016, 3, :o3, 1458864000
-
1
tz.transition 2016, 10, :o2, 1475362800
-
1
tz.transition 2017, 3, :o3, 1490313600
-
1
tz.transition 2017, 10, :o2, 1507417200
-
1
tz.transition 2018, 3, :o3, 1521763200
-
1
tz.transition 2018, 10, :o2, 1538866800
-
1
tz.transition 2019, 3, :o3, 1553817600
-
1
tz.transition 2019, 10, :o2, 1570316400
-
1
tz.transition 2020, 3, :o3, 1585267200
-
1
tz.transition 2020, 10, :o2, 1601766000
-
1
tz.transition 2021, 3, :o3, 1616716800
-
1
tz.transition 2021, 10, :o2, 1633215600
-
1
tz.transition 2022, 3, :o3, 1648166400
-
1
tz.transition 2022, 10, :o2, 1664665200
-
1
tz.transition 2023, 3, :o3, 1679616000
-
1
tz.transition 2023, 10, :o2, 1696719600
-
1
tz.transition 2024, 3, :o3, 1711670400
-
1
tz.transition 2024, 10, :o2, 1728169200
-
1
tz.transition 2025, 3, :o3, 1743120000
-
1
tz.transition 2025, 10, :o2, 1759618800
-
1
tz.transition 2026, 3, :o3, 1774569600
-
1
tz.transition 2026, 10, :o2, 1791068400
-
1
tz.transition 2027, 3, :o3, 1806019200
-
1
tz.transition 2027, 10, :o2, 1822604400
-
1
tz.transition 2028, 3, :o3, 1837468800
-
1
tz.transition 2028, 10, :o2, 1854572400
-
1
tz.transition 2029, 3, :o3, 1868918400
-
1
tz.transition 2029, 10, :o2, 1886022000
-
1
tz.transition 2030, 3, :o3, 1900972800
-
1
tz.transition 2030, 10, :o2, 1917471600
-
1
tz.transition 2031, 3, :o3, 1932422400
-
1
tz.transition 2031, 10, :o2, 1948921200
-
1
tz.transition 2032, 3, :o3, 1963872000
-
1
tz.transition 2032, 10, :o2, 1980370800
-
1
tz.transition 2033, 3, :o3, 1995321600
-
1
tz.transition 2033, 10, :o2, 2011820400
-
1
tz.transition 2034, 3, :o3, 2026771200
-
1
tz.transition 2034, 10, :o2, 2043874800
-
1
tz.transition 2035, 3, :o3, 2058220800
-
1
tz.transition 2035, 10, :o2, 2075324400
-
1
tz.transition 2036, 3, :o3, 2090275200
-
1
tz.transition 2036, 10, :o2, 2106774000
-
1
tz.transition 2037, 3, :o3, 2121724800
-
1
tz.transition 2037, 10, :o2, 2138223600
-
1
tz.transition 2038, 3, :o3, 4931017, 2
-
1
tz.transition 2038, 10, :o2, 59176787, 24
-
1
tz.transition 2039, 3, :o3, 4931745, 2
-
1
tz.transition 2039, 10, :o2, 59185523, 24
-
1
tz.transition 2040, 3, :o3, 4932473, 2
-
1
tz.transition 2040, 10, :o2, 59194427, 24
-
1
tz.transition 2041, 3, :o3, 4933215, 2
-
1
tz.transition 2041, 10, :o2, 59203163, 24
-
1
tz.transition 2042, 3, :o3, 4933943, 2
-
1
tz.transition 2042, 10, :o2, 59211899, 24
-
1
tz.transition 2043, 3, :o3, 4934671, 2
-
1
tz.transition 2043, 10, :o2, 59220635, 24
-
1
tz.transition 2044, 3, :o3, 4935399, 2
-
1
tz.transition 2044, 10, :o2, 59229371, 24
-
1
tz.transition 2045, 3, :o3, 4936127, 2
-
1
tz.transition 2045, 10, :o2, 59238275, 24
-
1
tz.transition 2046, 3, :o3, 4936855, 2
-
1
tz.transition 2046, 10, :o2, 59247011, 24
-
1
tz.transition 2047, 3, :o3, 4937597, 2
-
1
tz.transition 2047, 10, :o2, 59255747, 24
-
1
tz.transition 2048, 3, :o3, 4938325, 2
-
1
tz.transition 2048, 10, :o2, 59264483, 24
-
1
tz.transition 2049, 3, :o3, 4939053, 2
-
1
tz.transition 2049, 10, :o2, 59273219, 24
-
1
tz.transition 2050, 3, :o3, 4939781, 2
-
1
tz.transition 2050, 10, :o2, 59281955, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Kabul
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Kabul' do |tz|
-
1
tz.offset :o0, 16608, 0, :LMT
-
1
tz.offset :o1, 14400, 0, :AFT
-
1
tz.offset :o2, 16200, 0, :AFT
-
-
1
tz.transition 1889, 12, :o1, 2170231477, 900
-
1
tz.transition 1944, 12, :o2, 7294369, 3
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Kamchatka
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Kamchatka' do |tz|
-
1
tz.offset :o0, 38076, 0, :LMT
-
1
tz.offset :o1, 39600, 0, :PETT
-
1
tz.offset :o2, 43200, 0, :PETT
-
1
tz.offset :o3, 43200, 3600, :PETST
-
1
tz.offset :o4, 39600, 3600, :PETST
-
-
1
tz.transition 1922, 11, :o1, 17448250027, 7200
-
1
tz.transition 1930, 6, :o2, 58227553, 24
-
1
tz.transition 1981, 3, :o3, 354888000
-
1
tz.transition 1981, 9, :o2, 370695600
-
1
tz.transition 1982, 3, :o3, 386424000
-
1
tz.transition 1982, 9, :o2, 402231600
-
1
tz.transition 1983, 3, :o3, 417960000
-
1
tz.transition 1983, 9, :o2, 433767600
-
1
tz.transition 1984, 3, :o3, 449582400
-
1
tz.transition 1984, 9, :o2, 465314400
-
1
tz.transition 1985, 3, :o3, 481039200
-
1
tz.transition 1985, 9, :o2, 496764000
-
1
tz.transition 1986, 3, :o3, 512488800
-
1
tz.transition 1986, 9, :o2, 528213600
-
1
tz.transition 1987, 3, :o3, 543938400
-
1
tz.transition 1987, 9, :o2, 559663200
-
1
tz.transition 1988, 3, :o3, 575388000
-
1
tz.transition 1988, 9, :o2, 591112800
-
1
tz.transition 1989, 3, :o3, 606837600
-
1
tz.transition 1989, 9, :o2, 622562400
-
1
tz.transition 1990, 3, :o3, 638287200
-
1
tz.transition 1990, 9, :o2, 654616800
-
1
tz.transition 1991, 3, :o4, 670341600
-
1
tz.transition 1991, 9, :o1, 686070000
-
1
tz.transition 1992, 1, :o2, 695746800
-
1
tz.transition 1992, 3, :o3, 701780400
-
1
tz.transition 1992, 9, :o2, 717501600
-
1
tz.transition 1993, 3, :o3, 733240800
-
1
tz.transition 1993, 9, :o2, 748965600
-
1
tz.transition 1994, 3, :o3, 764690400
-
1
tz.transition 1994, 9, :o2, 780415200
-
1
tz.transition 1995, 3, :o3, 796140000
-
1
tz.transition 1995, 9, :o2, 811864800
-
1
tz.transition 1996, 3, :o3, 828194400
-
1
tz.transition 1996, 10, :o2, 846338400
-
1
tz.transition 1997, 3, :o3, 859644000
-
1
tz.transition 1997, 10, :o2, 877788000
-
1
tz.transition 1998, 3, :o3, 891093600
-
1
tz.transition 1998, 10, :o2, 909237600
-
1
tz.transition 1999, 3, :o3, 922543200
-
1
tz.transition 1999, 10, :o2, 941292000
-
1
tz.transition 2000, 3, :o3, 953992800
-
1
tz.transition 2000, 10, :o2, 972741600
-
1
tz.transition 2001, 3, :o3, 985442400
-
1
tz.transition 2001, 10, :o2, 1004191200
-
1
tz.transition 2002, 3, :o3, 1017496800
-
1
tz.transition 2002, 10, :o2, 1035640800
-
1
tz.transition 2003, 3, :o3, 1048946400
-
1
tz.transition 2003, 10, :o2, 1067090400
-
1
tz.transition 2004, 3, :o3, 1080396000
-
1
tz.transition 2004, 10, :o2, 1099144800
-
1
tz.transition 2005, 3, :o3, 1111845600
-
1
tz.transition 2005, 10, :o2, 1130594400
-
1
tz.transition 2006, 3, :o3, 1143295200
-
1
tz.transition 2006, 10, :o2, 1162044000
-
1
tz.transition 2007, 3, :o3, 1174744800
-
1
tz.transition 2007, 10, :o2, 1193493600
-
1
tz.transition 2008, 3, :o3, 1206799200
-
1
tz.transition 2008, 10, :o2, 1224943200
-
1
tz.transition 2009, 3, :o3, 1238248800
-
1
tz.transition 2009, 10, :o2, 1256392800
-
1
tz.transition 2010, 3, :o4, 1269698400
-
1
tz.transition 2010, 10, :o1, 1288450800
-
1
tz.transition 2011, 3, :o2, 1301151600
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Karachi
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Karachi' do |tz|
-
1
tz.offset :o0, 16092, 0, :LMT
-
1
tz.offset :o1, 19800, 0, :IST
-
1
tz.offset :o2, 19800, 3600, :IST
-
1
tz.offset :o3, 18000, 0, :KART
-
1
tz.offset :o4, 18000, 0, :PKT
-
1
tz.offset :o5, 18000, 3600, :PKST
-
-
1
tz.transition 1906, 12, :o1, 1934061051, 800
-
1
tz.transition 1942, 8, :o2, 116668957, 48
-
1
tz.transition 1945, 10, :o1, 116723675, 48
-
1
tz.transition 1951, 9, :o3, 116828125, 48
-
1
tz.transition 1971, 3, :o4, 38775600
-
1
tz.transition 2002, 4, :o5, 1018119660
-
1
tz.transition 2002, 10, :o4, 1033840860
-
1
tz.transition 2008, 5, :o5, 1212260400
-
1
tz.transition 2008, 10, :o4, 1225476000
-
1
tz.transition 2009, 4, :o5, 1239735600
-
1
tz.transition 2009, 10, :o4, 1257012000
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Kathmandu
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Kathmandu' do |tz|
-
1
tz.offset :o0, 20476, 0, :LMT
-
1
tz.offset :o1, 19800, 0, :IST
-
1
tz.offset :o2, 20700, 0, :NPT
-
-
1
tz.transition 1919, 12, :o1, 52322204081, 21600
-
1
tz.transition 1985, 12, :o2, 504901800
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Kolkata
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Kolkata' do |tz|
-
1
tz.offset :o0, 21208, 0, :LMT
-
1
tz.offset :o1, 21200, 0, :HMT
-
1
tz.offset :o2, 23400, 0, :BURT
-
1
tz.offset :o3, 19800, 0, :IST
-
1
tz.offset :o4, 19800, 3600, :IST
-
-
1
tz.transition 1879, 12, :o1, 26003324749, 10800
-
1
tz.transition 1941, 9, :o2, 524937943, 216
-
1
tz.transition 1942, 5, :o3, 116663723, 48
-
1
tz.transition 1942, 8, :o4, 116668957, 48
-
1
tz.transition 1945, 10, :o3, 116723675, 48
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Krasnoyarsk
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Krasnoyarsk' do |tz|
-
1
tz.offset :o0, 22280, 0, :LMT
-
1
tz.offset :o1, 21600, 0, :KRAT
-
1
tz.offset :o2, 25200, 0, :KRAT
-
1
tz.offset :o3, 25200, 3600, :KRAST
-
1
tz.offset :o4, 21600, 3600, :KRAST
-
1
tz.offset :o5, 28800, 0, :KRAT
-
-
1
tz.transition 1920, 1, :o1, 5232231163, 2160
-
1
tz.transition 1930, 6, :o2, 9704593, 4
-
1
tz.transition 1981, 3, :o3, 354906000
-
1
tz.transition 1981, 9, :o2, 370713600
-
1
tz.transition 1982, 3, :o3, 386442000
-
1
tz.transition 1982, 9, :o2, 402249600
-
1
tz.transition 1983, 3, :o3, 417978000
-
1
tz.transition 1983, 9, :o2, 433785600
-
1
tz.transition 1984, 3, :o3, 449600400
-
1
tz.transition 1984, 9, :o2, 465332400
-
1
tz.transition 1985, 3, :o3, 481057200
-
1
tz.transition 1985, 9, :o2, 496782000
-
1
tz.transition 1986, 3, :o3, 512506800
-
1
tz.transition 1986, 9, :o2, 528231600
-
1
tz.transition 1987, 3, :o3, 543956400
-
1
tz.transition 1987, 9, :o2, 559681200
-
1
tz.transition 1988, 3, :o3, 575406000
-
1
tz.transition 1988, 9, :o2, 591130800
-
1
tz.transition 1989, 3, :o3, 606855600
-
1
tz.transition 1989, 9, :o2, 622580400
-
1
tz.transition 1990, 3, :o3, 638305200
-
1
tz.transition 1990, 9, :o2, 654634800
-
1
tz.transition 1991, 3, :o4, 670359600
-
1
tz.transition 1991, 9, :o1, 686088000
-
1
tz.transition 1992, 1, :o2, 695764800
-
1
tz.transition 1992, 3, :o3, 701798400
-
1
tz.transition 1992, 9, :o2, 717519600
-
1
tz.transition 1993, 3, :o3, 733258800
-
1
tz.transition 1993, 9, :o2, 748983600
-
1
tz.transition 1994, 3, :o3, 764708400
-
1
tz.transition 1994, 9, :o2, 780433200
-
1
tz.transition 1995, 3, :o3, 796158000
-
1
tz.transition 1995, 9, :o2, 811882800
-
1
tz.transition 1996, 3, :o3, 828212400
-
1
tz.transition 1996, 10, :o2, 846356400
-
1
tz.transition 1997, 3, :o3, 859662000
-
1
tz.transition 1997, 10, :o2, 877806000
-
1
tz.transition 1998, 3, :o3, 891111600
-
1
tz.transition 1998, 10, :o2, 909255600
-
1
tz.transition 1999, 3, :o3, 922561200
-
1
tz.transition 1999, 10, :o2, 941310000
-
1
tz.transition 2000, 3, :o3, 954010800
-
1
tz.transition 2000, 10, :o2, 972759600
-
1
tz.transition 2001, 3, :o3, 985460400
-
1
tz.transition 2001, 10, :o2, 1004209200
-
1
tz.transition 2002, 3, :o3, 1017514800
-
1
tz.transition 2002, 10, :o2, 1035658800
-
1
tz.transition 2003, 3, :o3, 1048964400
-
1
tz.transition 2003, 10, :o2, 1067108400
-
1
tz.transition 2004, 3, :o3, 1080414000
-
1
tz.transition 2004, 10, :o2, 1099162800
-
1
tz.transition 2005, 3, :o3, 1111863600
-
1
tz.transition 2005, 10, :o2, 1130612400
-
1
tz.transition 2006, 3, :o3, 1143313200
-
1
tz.transition 2006, 10, :o2, 1162062000
-
1
tz.transition 2007, 3, :o3, 1174762800
-
1
tz.transition 2007, 10, :o2, 1193511600
-
1
tz.transition 2008, 3, :o3, 1206817200
-
1
tz.transition 2008, 10, :o2, 1224961200
-
1
tz.transition 2009, 3, :o3, 1238266800
-
1
tz.transition 2009, 10, :o2, 1256410800
-
1
tz.transition 2010, 3, :o3, 1269716400
-
1
tz.transition 2010, 10, :o2, 1288465200
-
1
tz.transition 2011, 3, :o5, 1301166000
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Kuala_Lumpur
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Kuala_Lumpur' do |tz|
-
1
tz.offset :o0, 24406, 0, :LMT
-
1
tz.offset :o1, 24925, 0, :SMT
-
1
tz.offset :o2, 25200, 0, :MALT
-
1
tz.offset :o3, 25200, 1200, :MALST
-
1
tz.offset :o4, 26400, 0, :MALT
-
1
tz.offset :o5, 27000, 0, :MALT
-
1
tz.offset :o6, 32400, 0, :JST
-
1
tz.offset :o7, 28800, 0, :MYT
-
-
1
tz.transition 1900, 12, :o1, 104344641397, 43200
-
1
tz.transition 1905, 5, :o2, 8353142363, 3456
-
1
tz.transition 1932, 12, :o3, 58249757, 24
-
1
tz.transition 1935, 12, :o4, 87414055, 36
-
1
tz.transition 1941, 8, :o5, 87488575, 36
-
1
tz.transition 1942, 2, :o6, 38886499, 16
-
1
tz.transition 1945, 9, :o5, 19453681, 8
-
1
tz.transition 1981, 12, :o7, 378664200
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Kuwait
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Kuwait' do |tz|
-
1
tz.offset :o0, 11516, 0, :LMT
-
1
tz.offset :o1, 10800, 0, :AST
-
-
1
tz.transition 1949, 12, :o1, 52558899121, 21600
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Magadan
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Magadan' do |tz|
-
1
tz.offset :o0, 36192, 0, :LMT
-
1
tz.offset :o1, 36000, 0, :MAGT
-
1
tz.offset :o2, 39600, 0, :MAGT
-
1
tz.offset :o3, 39600, 3600, :MAGST
-
1
tz.offset :o4, 36000, 3600, :MAGST
-
1
tz.offset :o5, 43200, 0, :MAGT
-
-
1
tz.transition 1924, 5, :o1, 2181516373, 900
-
1
tz.transition 1930, 6, :o2, 29113777, 12
-
1
tz.transition 1981, 3, :o3, 354891600
-
1
tz.transition 1981, 9, :o2, 370699200
-
1
tz.transition 1982, 3, :o3, 386427600
-
1
tz.transition 1982, 9, :o2, 402235200
-
1
tz.transition 1983, 3, :o3, 417963600
-
1
tz.transition 1983, 9, :o2, 433771200
-
1
tz.transition 1984, 3, :o3, 449586000
-
1
tz.transition 1984, 9, :o2, 465318000
-
1
tz.transition 1985, 3, :o3, 481042800
-
1
tz.transition 1985, 9, :o2, 496767600
-
1
tz.transition 1986, 3, :o3, 512492400
-
1
tz.transition 1986, 9, :o2, 528217200
-
1
tz.transition 1987, 3, :o3, 543942000
-
1
tz.transition 1987, 9, :o2, 559666800
-
1
tz.transition 1988, 3, :o3, 575391600
-
1
tz.transition 1988, 9, :o2, 591116400
-
1
tz.transition 1989, 3, :o3, 606841200
-
1
tz.transition 1989, 9, :o2, 622566000
-
1
tz.transition 1990, 3, :o3, 638290800
-
1
tz.transition 1990, 9, :o2, 654620400
-
1
tz.transition 1991, 3, :o4, 670345200
-
1
tz.transition 1991, 9, :o1, 686073600
-
1
tz.transition 1992, 1, :o2, 695750400
-
1
tz.transition 1992, 3, :o3, 701784000
-
1
tz.transition 1992, 9, :o2, 717505200
-
1
tz.transition 1993, 3, :o3, 733244400
-
1
tz.transition 1993, 9, :o2, 748969200
-
1
tz.transition 1994, 3, :o3, 764694000
-
1
tz.transition 1994, 9, :o2, 780418800
-
1
tz.transition 1995, 3, :o3, 796143600
-
1
tz.transition 1995, 9, :o2, 811868400
-
1
tz.transition 1996, 3, :o3, 828198000
-
1
tz.transition 1996, 10, :o2, 846342000
-
1
tz.transition 1997, 3, :o3, 859647600
-
1
tz.transition 1997, 10, :o2, 877791600
-
1
tz.transition 1998, 3, :o3, 891097200
-
1
tz.transition 1998, 10, :o2, 909241200
-
1
tz.transition 1999, 3, :o3, 922546800
-
1
tz.transition 1999, 10, :o2, 941295600
-
1
tz.transition 2000, 3, :o3, 953996400
-
1
tz.transition 2000, 10, :o2, 972745200
-
1
tz.transition 2001, 3, :o3, 985446000
-
1
tz.transition 2001, 10, :o2, 1004194800
-
1
tz.transition 2002, 3, :o3, 1017500400
-
1
tz.transition 2002, 10, :o2, 1035644400
-
1
tz.transition 2003, 3, :o3, 1048950000
-
1
tz.transition 2003, 10, :o2, 1067094000
-
1
tz.transition 2004, 3, :o3, 1080399600
-
1
tz.transition 2004, 10, :o2, 1099148400
-
1
tz.transition 2005, 3, :o3, 1111849200
-
1
tz.transition 2005, 10, :o2, 1130598000
-
1
tz.transition 2006, 3, :o3, 1143298800
-
1
tz.transition 2006, 10, :o2, 1162047600
-
1
tz.transition 2007, 3, :o3, 1174748400
-
1
tz.transition 2007, 10, :o2, 1193497200
-
1
tz.transition 2008, 3, :o3, 1206802800
-
1
tz.transition 2008, 10, :o2, 1224946800
-
1
tz.transition 2009, 3, :o3, 1238252400
-
1
tz.transition 2009, 10, :o2, 1256396400
-
1
tz.transition 2010, 3, :o3, 1269702000
-
1
tz.transition 2010, 10, :o2, 1288450800
-
1
tz.transition 2011, 3, :o5, 1301151600
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Muscat
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Muscat' do |tz|
-
1
tz.offset :o0, 14060, 0, :LMT
-
1
tz.offset :o1, 14400, 0, :GST
-
-
1
tz.transition 1919, 12, :o1, 10464441137, 4320
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Novosibirsk
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Novosibirsk' do |tz|
-
1
tz.offset :o0, 19900, 0, :LMT
-
1
tz.offset :o1, 21600, 0, :NOVT
-
1
tz.offset :o2, 25200, 0, :NOVT
-
1
tz.offset :o3, 25200, 3600, :NOVST
-
1
tz.offset :o4, 21600, 3600, :NOVST
-
-
1
tz.transition 1919, 12, :o1, 2092872833, 864
-
1
tz.transition 1930, 6, :o2, 9704593, 4
-
1
tz.transition 1981, 3, :o3, 354906000
-
1
tz.transition 1981, 9, :o2, 370713600
-
1
tz.transition 1982, 3, :o3, 386442000
-
1
tz.transition 1982, 9, :o2, 402249600
-
1
tz.transition 1983, 3, :o3, 417978000
-
1
tz.transition 1983, 9, :o2, 433785600
-
1
tz.transition 1984, 3, :o3, 449600400
-
1
tz.transition 1984, 9, :o2, 465332400
-
1
tz.transition 1985, 3, :o3, 481057200
-
1
tz.transition 1985, 9, :o2, 496782000
-
1
tz.transition 1986, 3, :o3, 512506800
-
1
tz.transition 1986, 9, :o2, 528231600
-
1
tz.transition 1987, 3, :o3, 543956400
-
1
tz.transition 1987, 9, :o2, 559681200
-
1
tz.transition 1988, 3, :o3, 575406000
-
1
tz.transition 1988, 9, :o2, 591130800
-
1
tz.transition 1989, 3, :o3, 606855600
-
1
tz.transition 1989, 9, :o2, 622580400
-
1
tz.transition 1990, 3, :o3, 638305200
-
1
tz.transition 1990, 9, :o2, 654634800
-
1
tz.transition 1991, 3, :o4, 670359600
-
1
tz.transition 1991, 9, :o1, 686088000
-
1
tz.transition 1992, 1, :o2, 695764800
-
1
tz.transition 1992, 3, :o3, 701798400
-
1
tz.transition 1992, 9, :o2, 717519600
-
1
tz.transition 1993, 3, :o3, 733258800
-
1
tz.transition 1993, 5, :o4, 738086400
-
1
tz.transition 1993, 9, :o1, 748987200
-
1
tz.transition 1994, 3, :o4, 764712000
-
1
tz.transition 1994, 9, :o1, 780436800
-
1
tz.transition 1995, 3, :o4, 796161600
-
1
tz.transition 1995, 9, :o1, 811886400
-
1
tz.transition 1996, 3, :o4, 828216000
-
1
tz.transition 1996, 10, :o1, 846360000
-
1
tz.transition 1997, 3, :o4, 859665600
-
1
tz.transition 1997, 10, :o1, 877809600
-
1
tz.transition 1998, 3, :o4, 891115200
-
1
tz.transition 1998, 10, :o1, 909259200
-
1
tz.transition 1999, 3, :o4, 922564800
-
1
tz.transition 1999, 10, :o1, 941313600
-
1
tz.transition 2000, 3, :o4, 954014400
-
1
tz.transition 2000, 10, :o1, 972763200
-
1
tz.transition 2001, 3, :o4, 985464000
-
1
tz.transition 2001, 10, :o1, 1004212800
-
1
tz.transition 2002, 3, :o4, 1017518400
-
1
tz.transition 2002, 10, :o1, 1035662400
-
1
tz.transition 2003, 3, :o4, 1048968000
-
1
tz.transition 2003, 10, :o1, 1067112000
-
1
tz.transition 2004, 3, :o4, 1080417600
-
1
tz.transition 2004, 10, :o1, 1099166400
-
1
tz.transition 2005, 3, :o4, 1111867200
-
1
tz.transition 2005, 10, :o1, 1130616000
-
1
tz.transition 2006, 3, :o4, 1143316800
-
1
tz.transition 2006, 10, :o1, 1162065600
-
1
tz.transition 2007, 3, :o4, 1174766400
-
1
tz.transition 2007, 10, :o1, 1193515200
-
1
tz.transition 2008, 3, :o4, 1206820800
-
1
tz.transition 2008, 10, :o1, 1224964800
-
1
tz.transition 2009, 3, :o4, 1238270400
-
1
tz.transition 2009, 10, :o1, 1256414400
-
1
tz.transition 2010, 3, :o4, 1269720000
-
1
tz.transition 2010, 10, :o1, 1288468800
-
1
tz.transition 2011, 3, :o2, 1301169600
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Rangoon
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Rangoon' do |tz|
-
1
tz.offset :o0, 23080, 0, :LMT
-
1
tz.offset :o1, 23076, 0, :RMT
-
1
tz.offset :o2, 23400, 0, :BURT
-
1
tz.offset :o3, 32400, 0, :JST
-
1
tz.offset :o4, 23400, 0, :MMT
-
-
1
tz.transition 1879, 12, :o1, 5200664903, 2160
-
1
tz.transition 1919, 12, :o2, 5813578159, 2400
-
1
tz.transition 1942, 4, :o3, 116663051, 48
-
1
tz.transition 1945, 5, :o4, 19452625, 8
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Riyadh
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Riyadh' do |tz|
-
1
tz.offset :o0, 11212, 0, :LMT
-
1
tz.offset :o1, 10800, 0, :AST
-
-
1
tz.transition 1949, 12, :o1, 52558899197, 21600
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Seoul
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Seoul' do |tz|
-
1
tz.offset :o0, 30472, 0, :LMT
-
1
tz.offset :o1, 30600, 0, :KST
-
1
tz.offset :o2, 32400, 0, :KST
-
1
tz.offset :o3, 28800, 0, :KST
-
1
tz.offset :o4, 28800, 3600, :KDT
-
1
tz.offset :o5, 32400, 3600, :KDT
-
-
1
tz.transition 1889, 12, :o1, 26042775991, 10800
-
1
tz.transition 1904, 11, :o2, 116007127, 48
-
1
tz.transition 1927, 12, :o1, 19401969, 8
-
1
tz.transition 1931, 12, :o2, 116481943, 48
-
1
tz.transition 1954, 3, :o3, 19478577, 8
-
1
tz.transition 1960, 5, :o4, 14622415, 6
-
1
tz.transition 1960, 9, :o3, 19497521, 8
-
1
tz.transition 1961, 8, :o1, 14625127, 6
-
1
tz.transition 1968, 9, :o2, 117126247, 48
-
1
tz.transition 1987, 5, :o5, 547570800
-
1
tz.transition 1987, 10, :o2, 560872800
-
1
tz.transition 1988, 5, :o5, 579020400
-
1
tz.transition 1988, 10, :o2, 592322400
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Shanghai
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Shanghai' do |tz|
-
1
tz.offset :o0, 29152, 0, :LMT
-
1
tz.offset :o1, 28800, 0, :CST
-
1
tz.offset :o2, 28800, 3600, :CDT
-
-
1
tz.transition 1927, 12, :o1, 6548164639, 2700
-
1
tz.transition 1940, 6, :o2, 14578699, 6
-
1
tz.transition 1940, 9, :o1, 19439225, 8
-
1
tz.transition 1941, 3, :o2, 14580415, 6
-
1
tz.transition 1941, 9, :o1, 19442145, 8
-
1
tz.transition 1986, 5, :o2, 515520000
-
1
tz.transition 1986, 9, :o1, 527007600
-
1
tz.transition 1987, 4, :o2, 545155200
-
1
tz.transition 1987, 9, :o1, 558457200
-
1
tz.transition 1988, 4, :o2, 576604800
-
1
tz.transition 1988, 9, :o1, 589906800
-
1
tz.transition 1989, 4, :o2, 608659200
-
1
tz.transition 1989, 9, :o1, 621961200
-
1
tz.transition 1990, 4, :o2, 640108800
-
1
tz.transition 1990, 9, :o1, 653410800
-
1
tz.transition 1991, 4, :o2, 671558400
-
1
tz.transition 1991, 9, :o1, 684860400
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Singapore
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Singapore' do |tz|
-
1
tz.offset :o0, 24925, 0, :LMT
-
1
tz.offset :o1, 24925, 0, :SMT
-
1
tz.offset :o2, 25200, 0, :MALT
-
1
tz.offset :o3, 25200, 1200, :MALST
-
1
tz.offset :o4, 26400, 0, :MALT
-
1
tz.offset :o5, 27000, 0, :MALT
-
1
tz.offset :o6, 32400, 0, :JST
-
1
tz.offset :o7, 27000, 0, :SGT
-
1
tz.offset :o8, 28800, 0, :SGT
-
-
1
tz.transition 1900, 12, :o1, 8347571291, 3456
-
1
tz.transition 1905, 5, :o2, 8353142363, 3456
-
1
tz.transition 1932, 12, :o3, 58249757, 24
-
1
tz.transition 1935, 12, :o4, 87414055, 36
-
1
tz.transition 1941, 8, :o5, 87488575, 36
-
1
tz.transition 1942, 2, :o6, 38886499, 16
-
1
tz.transition 1945, 9, :o5, 19453681, 8
-
1
tz.transition 1965, 8, :o7, 39023699, 16
-
1
tz.transition 1981, 12, :o8, 378664200
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Taipei
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Taipei' do |tz|
-
1
tz.offset :o0, 29160, 0, :LMT
-
1
tz.offset :o1, 28800, 0, :CST
-
1
tz.offset :o2, 28800, 3600, :CDT
-
-
1
tz.transition 1895, 12, :o1, 193084733, 80
-
1
tz.transition 1945, 4, :o2, 14589457, 6
-
1
tz.transition 1945, 9, :o1, 19453833, 8
-
1
tz.transition 1946, 4, :o2, 14591647, 6
-
1
tz.transition 1946, 9, :o1, 19456753, 8
-
1
tz.transition 1947, 4, :o2, 14593837, 6
-
1
tz.transition 1947, 9, :o1, 19459673, 8
-
1
tz.transition 1948, 4, :o2, 14596033, 6
-
1
tz.transition 1948, 9, :o1, 19462601, 8
-
1
tz.transition 1949, 4, :o2, 14598223, 6
-
1
tz.transition 1949, 9, :o1, 19465521, 8
-
1
tz.transition 1950, 4, :o2, 14600413, 6
-
1
tz.transition 1950, 9, :o1, 19468441, 8
-
1
tz.transition 1951, 4, :o2, 14602603, 6
-
1
tz.transition 1951, 9, :o1, 19471361, 8
-
1
tz.transition 1952, 2, :o2, 14604433, 6
-
1
tz.transition 1952, 10, :o1, 19474537, 8
-
1
tz.transition 1953, 3, :o2, 14606809, 6
-
1
tz.transition 1953, 10, :o1, 19477457, 8
-
1
tz.transition 1954, 3, :o2, 14608999, 6
-
1
tz.transition 1954, 10, :o1, 19480377, 8
-
1
tz.transition 1955, 3, :o2, 14611189, 6
-
1
tz.transition 1955, 9, :o1, 19483049, 8
-
1
tz.transition 1956, 3, :o2, 14613385, 6
-
1
tz.transition 1956, 9, :o1, 19485977, 8
-
1
tz.transition 1957, 3, :o2, 14615575, 6
-
1
tz.transition 1957, 9, :o1, 19488897, 8
-
1
tz.transition 1958, 3, :o2, 14617765, 6
-
1
tz.transition 1958, 9, :o1, 19491817, 8
-
1
tz.transition 1959, 3, :o2, 14619955, 6
-
1
tz.transition 1959, 9, :o1, 19494737, 8
-
1
tz.transition 1960, 5, :o2, 14622517, 6
-
1
tz.transition 1960, 9, :o1, 19497665, 8
-
1
tz.transition 1961, 5, :o2, 14624707, 6
-
1
tz.transition 1961, 9, :o1, 19500585, 8
-
1
tz.transition 1974, 3, :o2, 133977600
-
1
tz.transition 1974, 9, :o1, 149785200
-
1
tz.transition 1975, 3, :o2, 165513600
-
1
tz.transition 1975, 9, :o1, 181321200
-
1
tz.transition 1979, 6, :o2, 299520000
-
1
tz.transition 1979, 9, :o1, 307465200
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Tashkent
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Tashkent' do |tz|
-
1
tz.offset :o0, 16632, 0, :LMT
-
1
tz.offset :o1, 18000, 0, :TAST
-
1
tz.offset :o2, 21600, 0, :TAST
-
1
tz.offset :o3, 21600, 3600, :TASST
-
1
tz.offset :o4, 18000, 3600, :TASST
-
1
tz.offset :o5, 18000, 3600, :UZST
-
1
tz.offset :o6, 18000, 0, :UZT
-
-
1
tz.transition 1924, 5, :o1, 969562923, 400
-
1
tz.transition 1930, 6, :o2, 58227559, 24
-
1
tz.transition 1981, 3, :o3, 354909600
-
1
tz.transition 1981, 9, :o2, 370717200
-
1
tz.transition 1982, 3, :o3, 386445600
-
1
tz.transition 1982, 9, :o2, 402253200
-
1
tz.transition 1983, 3, :o3, 417981600
-
1
tz.transition 1983, 9, :o2, 433789200
-
1
tz.transition 1984, 3, :o3, 449604000
-
1
tz.transition 1984, 9, :o2, 465336000
-
1
tz.transition 1985, 3, :o3, 481060800
-
1
tz.transition 1985, 9, :o2, 496785600
-
1
tz.transition 1986, 3, :o3, 512510400
-
1
tz.transition 1986, 9, :o2, 528235200
-
1
tz.transition 1987, 3, :o3, 543960000
-
1
tz.transition 1987, 9, :o2, 559684800
-
1
tz.transition 1988, 3, :o3, 575409600
-
1
tz.transition 1988, 9, :o2, 591134400
-
1
tz.transition 1989, 3, :o3, 606859200
-
1
tz.transition 1989, 9, :o2, 622584000
-
1
tz.transition 1990, 3, :o3, 638308800
-
1
tz.transition 1990, 9, :o2, 654638400
-
1
tz.transition 1991, 3, :o4, 670363200
-
1
tz.transition 1991, 8, :o5, 683661600
-
1
tz.transition 1991, 9, :o6, 686091600
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Tbilisi
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Tbilisi' do |tz|
-
1
tz.offset :o0, 10756, 0, :LMT
-
1
tz.offset :o1, 10756, 0, :TBMT
-
1
tz.offset :o2, 10800, 0, :TBIT
-
1
tz.offset :o3, 14400, 0, :TBIT
-
1
tz.offset :o4, 14400, 3600, :TBIST
-
1
tz.offset :o5, 10800, 3600, :TBIST
-
1
tz.offset :o6, 10800, 3600, :GEST
-
1
tz.offset :o7, 10800, 0, :GET
-
1
tz.offset :o8, 14400, 0, :GET
-
1
tz.offset :o9, 14400, 3600, :GEST
-
-
1
tz.transition 1879, 12, :o1, 52006652111, 21600
-
1
tz.transition 1924, 5, :o2, 52356399311, 21600
-
1
tz.transition 1957, 2, :o3, 19487187, 8
-
1
tz.transition 1981, 3, :o4, 354916800
-
1
tz.transition 1981, 9, :o3, 370724400
-
1
tz.transition 1982, 3, :o4, 386452800
-
1
tz.transition 1982, 9, :o3, 402260400
-
1
tz.transition 1983, 3, :o4, 417988800
-
1
tz.transition 1983, 9, :o3, 433796400
-
1
tz.transition 1984, 3, :o4, 449611200
-
1
tz.transition 1984, 9, :o3, 465343200
-
1
tz.transition 1985, 3, :o4, 481068000
-
1
tz.transition 1985, 9, :o3, 496792800
-
1
tz.transition 1986, 3, :o4, 512517600
-
1
tz.transition 1986, 9, :o3, 528242400
-
1
tz.transition 1987, 3, :o4, 543967200
-
1
tz.transition 1987, 9, :o3, 559692000
-
1
tz.transition 1988, 3, :o4, 575416800
-
1
tz.transition 1988, 9, :o3, 591141600
-
1
tz.transition 1989, 3, :o4, 606866400
-
1
tz.transition 1989, 9, :o3, 622591200
-
1
tz.transition 1990, 3, :o4, 638316000
-
1
tz.transition 1990, 9, :o3, 654645600
-
1
tz.transition 1991, 3, :o5, 670370400
-
1
tz.transition 1991, 4, :o6, 671140800
-
1
tz.transition 1991, 9, :o7, 686098800
-
1
tz.transition 1992, 3, :o6, 701816400
-
1
tz.transition 1992, 9, :o7, 717537600
-
1
tz.transition 1993, 3, :o6, 733266000
-
1
tz.transition 1993, 9, :o7, 748987200
-
1
tz.transition 1994, 3, :o6, 764715600
-
1
tz.transition 1994, 9, :o8, 780436800
-
1
tz.transition 1995, 3, :o9, 796161600
-
1
tz.transition 1995, 9, :o8, 811882800
-
1
tz.transition 1996, 3, :o9, 828216000
-
1
tz.transition 1997, 3, :o9, 859662000
-
1
tz.transition 1997, 10, :o8, 877806000
-
1
tz.transition 1998, 3, :o9, 891115200
-
1
tz.transition 1998, 10, :o8, 909255600
-
1
tz.transition 1999, 3, :o9, 922564800
-
1
tz.transition 1999, 10, :o8, 941310000
-
1
tz.transition 2000, 3, :o9, 954014400
-
1
tz.transition 2000, 10, :o8, 972759600
-
1
tz.transition 2001, 3, :o9, 985464000
-
1
tz.transition 2001, 10, :o8, 1004209200
-
1
tz.transition 2002, 3, :o9, 1017518400
-
1
tz.transition 2002, 10, :o8, 1035658800
-
1
tz.transition 2003, 3, :o9, 1048968000
-
1
tz.transition 2003, 10, :o8, 1067108400
-
1
tz.transition 2004, 3, :o9, 1080417600
-
1
tz.transition 2004, 6, :o6, 1088276400
-
1
tz.transition 2004, 10, :o7, 1099177200
-
1
tz.transition 2005, 3, :o8, 1111878000
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Tehran
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Tehran' do |tz|
-
1
tz.offset :o0, 12344, 0, :LMT
-
1
tz.offset :o1, 12344, 0, :TMT
-
1
tz.offset :o2, 12600, 0, :IRST
-
1
tz.offset :o3, 14400, 0, :IRST
-
1
tz.offset :o4, 14400, 3600, :IRDT
-
1
tz.offset :o5, 12600, 3600, :IRDT
-
-
1
tz.transition 1915, 12, :o1, 26145324257, 10800
-
1
tz.transition 1945, 12, :o2, 26263670657, 10800
-
1
tz.transition 1977, 10, :o3, 247177800
-
1
tz.transition 1978, 3, :o4, 259272000
-
1
tz.transition 1978, 10, :o3, 277758000
-
1
tz.transition 1978, 12, :o2, 283982400
-
1
tz.transition 1979, 3, :o5, 290809800
-
1
tz.transition 1979, 9, :o2, 306531000
-
1
tz.transition 1980, 3, :o5, 322432200
-
1
tz.transition 1980, 9, :o2, 338499000
-
1
tz.transition 1991, 5, :o5, 673216200
-
1
tz.transition 1991, 9, :o2, 685481400
-
1
tz.transition 1992, 3, :o5, 701209800
-
1
tz.transition 1992, 9, :o2, 717103800
-
1
tz.transition 1993, 3, :o5, 732745800
-
1
tz.transition 1993, 9, :o2, 748639800
-
1
tz.transition 1994, 3, :o5, 764281800
-
1
tz.transition 1994, 9, :o2, 780175800
-
1
tz.transition 1995, 3, :o5, 795817800
-
1
tz.transition 1995, 9, :o2, 811711800
-
1
tz.transition 1996, 3, :o5, 827353800
-
1
tz.transition 1996, 9, :o2, 843247800
-
1
tz.transition 1997, 3, :o5, 858976200
-
1
tz.transition 1997, 9, :o2, 874870200
-
1
tz.transition 1998, 3, :o5, 890512200
-
1
tz.transition 1998, 9, :o2, 906406200
-
1
tz.transition 1999, 3, :o5, 922048200
-
1
tz.transition 1999, 9, :o2, 937942200
-
1
tz.transition 2000, 3, :o5, 953584200
-
1
tz.transition 2000, 9, :o2, 969478200
-
1
tz.transition 2001, 3, :o5, 985206600
-
1
tz.transition 2001, 9, :o2, 1001100600
-
1
tz.transition 2002, 3, :o5, 1016742600
-
1
tz.transition 2002, 9, :o2, 1032636600
-
1
tz.transition 2003, 3, :o5, 1048278600
-
1
tz.transition 2003, 9, :o2, 1064172600
-
1
tz.transition 2004, 3, :o5, 1079814600
-
1
tz.transition 2004, 9, :o2, 1095708600
-
1
tz.transition 2005, 3, :o5, 1111437000
-
1
tz.transition 2005, 9, :o2, 1127331000
-
1
tz.transition 2008, 3, :o5, 1206045000
-
1
tz.transition 2008, 9, :o2, 1221939000
-
1
tz.transition 2009, 3, :o5, 1237667400
-
1
tz.transition 2009, 9, :o2, 1253561400
-
1
tz.transition 2010, 3, :o5, 1269203400
-
1
tz.transition 2010, 9, :o2, 1285097400
-
1
tz.transition 2011, 3, :o5, 1300739400
-
1
tz.transition 2011, 9, :o2, 1316633400
-
1
tz.transition 2012, 3, :o5, 1332275400
-
1
tz.transition 2012, 9, :o2, 1348169400
-
1
tz.transition 2013, 3, :o5, 1363897800
-
1
tz.transition 2013, 9, :o2, 1379791800
-
1
tz.transition 2014, 3, :o5, 1395433800
-
1
tz.transition 2014, 9, :o2, 1411327800
-
1
tz.transition 2015, 3, :o5, 1426969800
-
1
tz.transition 2015, 9, :o2, 1442863800
-
1
tz.transition 2016, 3, :o5, 1458505800
-
1
tz.transition 2016, 9, :o2, 1474399800
-
1
tz.transition 2017, 3, :o5, 1490128200
-
1
tz.transition 2017, 9, :o2, 1506022200
-
1
tz.transition 2018, 3, :o5, 1521664200
-
1
tz.transition 2018, 9, :o2, 1537558200
-
1
tz.transition 2019, 3, :o5, 1553200200
-
1
tz.transition 2019, 9, :o2, 1569094200
-
1
tz.transition 2020, 3, :o5, 1584736200
-
1
tz.transition 2020, 9, :o2, 1600630200
-
1
tz.transition 2021, 3, :o5, 1616358600
-
1
tz.transition 2021, 9, :o2, 1632252600
-
1
tz.transition 2022, 3, :o5, 1647894600
-
1
tz.transition 2022, 9, :o2, 1663788600
-
1
tz.transition 2023, 3, :o5, 1679430600
-
1
tz.transition 2023, 9, :o2, 1695324600
-
1
tz.transition 2024, 3, :o5, 1710966600
-
1
tz.transition 2024, 9, :o2, 1726860600
-
1
tz.transition 2025, 3, :o5, 1742589000
-
1
tz.transition 2025, 9, :o2, 1758483000
-
1
tz.transition 2026, 3, :o5, 1774125000
-
1
tz.transition 2026, 9, :o2, 1790019000
-
1
tz.transition 2027, 3, :o5, 1805661000
-
1
tz.transition 2027, 9, :o2, 1821555000
-
1
tz.transition 2028, 3, :o5, 1837197000
-
1
tz.transition 2028, 9, :o2, 1853091000
-
1
tz.transition 2029, 3, :o5, 1868733000
-
1
tz.transition 2029, 9, :o2, 1884627000
-
1
tz.transition 2030, 3, :o5, 1900355400
-
1
tz.transition 2030, 9, :o2, 1916249400
-
1
tz.transition 2031, 3, :o5, 1931891400
-
1
tz.transition 2031, 9, :o2, 1947785400
-
1
tz.transition 2032, 3, :o5, 1963427400
-
1
tz.transition 2032, 9, :o2, 1979321400
-
1
tz.transition 2033, 3, :o5, 1994963400
-
1
tz.transition 2033, 9, :o2, 2010857400
-
1
tz.transition 2034, 3, :o5, 2026585800
-
1
tz.transition 2034, 9, :o2, 2042479800
-
1
tz.transition 2035, 3, :o5, 2058121800
-
1
tz.transition 2035, 9, :o2, 2074015800
-
1
tz.transition 2036, 3, :o5, 2089657800
-
1
tz.transition 2036, 9, :o2, 2105551800
-
1
tz.transition 2037, 3, :o5, 2121193800
-
1
tz.transition 2037, 9, :o2, 2137087800
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Tokyo
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Tokyo' do |tz|
-
1
tz.offset :o0, 33539, 0, :LMT
-
1
tz.offset :o1, 32400, 0, :JST
-
1
tz.offset :o2, 32400, 0, :CJT
-
1
tz.offset :o3, 32400, 3600, :JDT
-
-
1
tz.transition 1887, 12, :o1, 19285097, 8
-
1
tz.transition 1895, 12, :o2, 19308473, 8
-
1
tz.transition 1937, 12, :o1, 19431193, 8
-
1
tz.transition 1948, 5, :o3, 58384157, 24
-
1
tz.transition 1948, 9, :o1, 14596831, 6
-
1
tz.transition 1949, 4, :o3, 58392221, 24
-
1
tz.transition 1949, 9, :o1, 14599015, 6
-
1
tz.transition 1950, 5, :o3, 58401797, 24
-
1
tz.transition 1950, 9, :o1, 14601199, 6
-
1
tz.transition 1951, 5, :o3, 58410533, 24
-
1
tz.transition 1951, 9, :o1, 14603383, 6
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Ulaanbaatar
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Ulaanbaatar' do |tz|
-
1
tz.offset :o0, 25652, 0, :LMT
-
1
tz.offset :o1, 25200, 0, :ULAT
-
1
tz.offset :o2, 28800, 0, :ULAT
-
1
tz.offset :o3, 28800, 3600, :ULAST
-
-
1
tz.transition 1905, 7, :o1, 52208457187, 21600
-
1
tz.transition 1977, 12, :o2, 252435600
-
1
tz.transition 1983, 3, :o3, 417974400
-
1
tz.transition 1983, 9, :o2, 433782000
-
1
tz.transition 1984, 3, :o3, 449596800
-
1
tz.transition 1984, 9, :o2, 465318000
-
1
tz.transition 1985, 3, :o3, 481046400
-
1
tz.transition 1985, 9, :o2, 496767600
-
1
tz.transition 1986, 3, :o3, 512496000
-
1
tz.transition 1986, 9, :o2, 528217200
-
1
tz.transition 1987, 3, :o3, 543945600
-
1
tz.transition 1987, 9, :o2, 559666800
-
1
tz.transition 1988, 3, :o3, 575395200
-
1
tz.transition 1988, 9, :o2, 591116400
-
1
tz.transition 1989, 3, :o3, 606844800
-
1
tz.transition 1989, 9, :o2, 622566000
-
1
tz.transition 1990, 3, :o3, 638294400
-
1
tz.transition 1990, 9, :o2, 654620400
-
1
tz.transition 1991, 3, :o3, 670348800
-
1
tz.transition 1991, 9, :o2, 686070000
-
1
tz.transition 1992, 3, :o3, 701798400
-
1
tz.transition 1992, 9, :o2, 717519600
-
1
tz.transition 1993, 3, :o3, 733248000
-
1
tz.transition 1993, 9, :o2, 748969200
-
1
tz.transition 1994, 3, :o3, 764697600
-
1
tz.transition 1994, 9, :o2, 780418800
-
1
tz.transition 1995, 3, :o3, 796147200
-
1
tz.transition 1995, 9, :o2, 811868400
-
1
tz.transition 1996, 3, :o3, 828201600
-
1
tz.transition 1996, 9, :o2, 843922800
-
1
tz.transition 1997, 3, :o3, 859651200
-
1
tz.transition 1997, 9, :o2, 875372400
-
1
tz.transition 1998, 3, :o3, 891100800
-
1
tz.transition 1998, 9, :o2, 906822000
-
1
tz.transition 2001, 4, :o3, 988394400
-
1
tz.transition 2001, 9, :o2, 1001696400
-
1
tz.transition 2002, 3, :o3, 1017424800
-
1
tz.transition 2002, 9, :o2, 1033146000
-
1
tz.transition 2003, 3, :o3, 1048874400
-
1
tz.transition 2003, 9, :o2, 1064595600
-
1
tz.transition 2004, 3, :o3, 1080324000
-
1
tz.transition 2004, 9, :o2, 1096045200
-
1
tz.transition 2005, 3, :o3, 1111773600
-
1
tz.transition 2005, 9, :o2, 1127494800
-
1
tz.transition 2006, 3, :o3, 1143223200
-
1
tz.transition 2006, 9, :o2, 1159549200
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Urumqi
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Urumqi' do |tz|
-
1
tz.offset :o0, 21020, 0, :LMT
-
1
tz.offset :o1, 21600, 0, :URUT
-
1
tz.offset :o2, 28800, 0, :CST
-
1
tz.offset :o3, 28800, 3600, :CDT
-
-
1
tz.transition 1927, 12, :o1, 10477063829, 4320
-
1
tz.transition 1980, 4, :o2, 325965600
-
1
tz.transition 1986, 5, :o3, 515520000
-
1
tz.transition 1986, 9, :o2, 527007600
-
1
tz.transition 1987, 4, :o3, 545155200
-
1
tz.transition 1987, 9, :o2, 558457200
-
1
tz.transition 1988, 4, :o3, 576604800
-
1
tz.transition 1988, 9, :o2, 589906800
-
1
tz.transition 1989, 4, :o3, 608659200
-
1
tz.transition 1989, 9, :o2, 621961200
-
1
tz.transition 1990, 4, :o3, 640108800
-
1
tz.transition 1990, 9, :o2, 653410800
-
1
tz.transition 1991, 4, :o3, 671558400
-
1
tz.transition 1991, 9, :o2, 684860400
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Vladivostok
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Vladivostok' do |tz|
-
1
tz.offset :o0, 31664, 0, :LMT
-
1
tz.offset :o1, 32400, 0, :VLAT
-
1
tz.offset :o2, 36000, 0, :VLAT
-
1
tz.offset :o3, 36000, 3600, :VLAST
-
1
tz.offset :o4, 32400, 3600, :VLASST
-
1
tz.offset :o5, 32400, 0, :VLAST
-
1
tz.offset :o6, 39600, 0, :VLAT
-
-
1
tz.transition 1922, 11, :o1, 13086214921, 5400
-
1
tz.transition 1930, 6, :o2, 19409185, 8
-
1
tz.transition 1981, 3, :o3, 354895200
-
1
tz.transition 1981, 9, :o2, 370702800
-
1
tz.transition 1982, 3, :o3, 386431200
-
1
tz.transition 1982, 9, :o2, 402238800
-
1
tz.transition 1983, 3, :o3, 417967200
-
1
tz.transition 1983, 9, :o2, 433774800
-
1
tz.transition 1984, 3, :o3, 449589600
-
1
tz.transition 1984, 9, :o2, 465321600
-
1
tz.transition 1985, 3, :o3, 481046400
-
1
tz.transition 1985, 9, :o2, 496771200
-
1
tz.transition 1986, 3, :o3, 512496000
-
1
tz.transition 1986, 9, :o2, 528220800
-
1
tz.transition 1987, 3, :o3, 543945600
-
1
tz.transition 1987, 9, :o2, 559670400
-
1
tz.transition 1988, 3, :o3, 575395200
-
1
tz.transition 1988, 9, :o2, 591120000
-
1
tz.transition 1989, 3, :o3, 606844800
-
1
tz.transition 1989, 9, :o2, 622569600
-
1
tz.transition 1990, 3, :o3, 638294400
-
1
tz.transition 1990, 9, :o2, 654624000
-
1
tz.transition 1991, 3, :o4, 670348800
-
1
tz.transition 1991, 9, :o5, 686077200
-
1
tz.transition 1992, 1, :o2, 695754000
-
1
tz.transition 1992, 3, :o3, 701787600
-
1
tz.transition 1992, 9, :o2, 717508800
-
1
tz.transition 1993, 3, :o3, 733248000
-
1
tz.transition 1993, 9, :o2, 748972800
-
1
tz.transition 1994, 3, :o3, 764697600
-
1
tz.transition 1994, 9, :o2, 780422400
-
1
tz.transition 1995, 3, :o3, 796147200
-
1
tz.transition 1995, 9, :o2, 811872000
-
1
tz.transition 1996, 3, :o3, 828201600
-
1
tz.transition 1996, 10, :o2, 846345600
-
1
tz.transition 1997, 3, :o3, 859651200
-
1
tz.transition 1997, 10, :o2, 877795200
-
1
tz.transition 1998, 3, :o3, 891100800
-
1
tz.transition 1998, 10, :o2, 909244800
-
1
tz.transition 1999, 3, :o3, 922550400
-
1
tz.transition 1999, 10, :o2, 941299200
-
1
tz.transition 2000, 3, :o3, 954000000
-
1
tz.transition 2000, 10, :o2, 972748800
-
1
tz.transition 2001, 3, :o3, 985449600
-
1
tz.transition 2001, 10, :o2, 1004198400
-
1
tz.transition 2002, 3, :o3, 1017504000
-
1
tz.transition 2002, 10, :o2, 1035648000
-
1
tz.transition 2003, 3, :o3, 1048953600
-
1
tz.transition 2003, 10, :o2, 1067097600
-
1
tz.transition 2004, 3, :o3, 1080403200
-
1
tz.transition 2004, 10, :o2, 1099152000
-
1
tz.transition 2005, 3, :o3, 1111852800
-
1
tz.transition 2005, 10, :o2, 1130601600
-
1
tz.transition 2006, 3, :o3, 1143302400
-
1
tz.transition 2006, 10, :o2, 1162051200
-
1
tz.transition 2007, 3, :o3, 1174752000
-
1
tz.transition 2007, 10, :o2, 1193500800
-
1
tz.transition 2008, 3, :o3, 1206806400
-
1
tz.transition 2008, 10, :o2, 1224950400
-
1
tz.transition 2009, 3, :o3, 1238256000
-
1
tz.transition 2009, 10, :o2, 1256400000
-
1
tz.transition 2010, 3, :o3, 1269705600
-
1
tz.transition 2010, 10, :o2, 1288454400
-
1
tz.transition 2011, 3, :o6, 1301155200
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Yakutsk
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Yakutsk' do |tz|
-
1
tz.offset :o0, 31120, 0, :LMT
-
1
tz.offset :o1, 28800, 0, :YAKT
-
1
tz.offset :o2, 32400, 0, :YAKT
-
1
tz.offset :o3, 32400, 3600, :YAKST
-
1
tz.offset :o4, 28800, 3600, :YAKST
-
1
tz.offset :o5, 36000, 0, :YAKT
-
-
1
tz.transition 1919, 12, :o1, 2616091711, 1080
-
1
tz.transition 1930, 6, :o2, 14556889, 6
-
1
tz.transition 1981, 3, :o3, 354898800
-
1
tz.transition 1981, 9, :o2, 370706400
-
1
tz.transition 1982, 3, :o3, 386434800
-
1
tz.transition 1982, 9, :o2, 402242400
-
1
tz.transition 1983, 3, :o3, 417970800
-
1
tz.transition 1983, 9, :o2, 433778400
-
1
tz.transition 1984, 3, :o3, 449593200
-
1
tz.transition 1984, 9, :o2, 465325200
-
1
tz.transition 1985, 3, :o3, 481050000
-
1
tz.transition 1985, 9, :o2, 496774800
-
1
tz.transition 1986, 3, :o3, 512499600
-
1
tz.transition 1986, 9, :o2, 528224400
-
1
tz.transition 1987, 3, :o3, 543949200
-
1
tz.transition 1987, 9, :o2, 559674000
-
1
tz.transition 1988, 3, :o3, 575398800
-
1
tz.transition 1988, 9, :o2, 591123600
-
1
tz.transition 1989, 3, :o3, 606848400
-
1
tz.transition 1989, 9, :o2, 622573200
-
1
tz.transition 1990, 3, :o3, 638298000
-
1
tz.transition 1990, 9, :o2, 654627600
-
1
tz.transition 1991, 3, :o4, 670352400
-
1
tz.transition 1991, 9, :o1, 686080800
-
1
tz.transition 1992, 1, :o2, 695757600
-
1
tz.transition 1992, 3, :o3, 701791200
-
1
tz.transition 1992, 9, :o2, 717512400
-
1
tz.transition 1993, 3, :o3, 733251600
-
1
tz.transition 1993, 9, :o2, 748976400
-
1
tz.transition 1994, 3, :o3, 764701200
-
1
tz.transition 1994, 9, :o2, 780426000
-
1
tz.transition 1995, 3, :o3, 796150800
-
1
tz.transition 1995, 9, :o2, 811875600
-
1
tz.transition 1996, 3, :o3, 828205200
-
1
tz.transition 1996, 10, :o2, 846349200
-
1
tz.transition 1997, 3, :o3, 859654800
-
1
tz.transition 1997, 10, :o2, 877798800
-
1
tz.transition 1998, 3, :o3, 891104400
-
1
tz.transition 1998, 10, :o2, 909248400
-
1
tz.transition 1999, 3, :o3, 922554000
-
1
tz.transition 1999, 10, :o2, 941302800
-
1
tz.transition 2000, 3, :o3, 954003600
-
1
tz.transition 2000, 10, :o2, 972752400
-
1
tz.transition 2001, 3, :o3, 985453200
-
1
tz.transition 2001, 10, :o2, 1004202000
-
1
tz.transition 2002, 3, :o3, 1017507600
-
1
tz.transition 2002, 10, :o2, 1035651600
-
1
tz.transition 2003, 3, :o3, 1048957200
-
1
tz.transition 2003, 10, :o2, 1067101200
-
1
tz.transition 2004, 3, :o3, 1080406800
-
1
tz.transition 2004, 10, :o2, 1099155600
-
1
tz.transition 2005, 3, :o3, 1111856400
-
1
tz.transition 2005, 10, :o2, 1130605200
-
1
tz.transition 2006, 3, :o3, 1143306000
-
1
tz.transition 2006, 10, :o2, 1162054800
-
1
tz.transition 2007, 3, :o3, 1174755600
-
1
tz.transition 2007, 10, :o2, 1193504400
-
1
tz.transition 2008, 3, :o3, 1206810000
-
1
tz.transition 2008, 10, :o2, 1224954000
-
1
tz.transition 2009, 3, :o3, 1238259600
-
1
tz.transition 2009, 10, :o2, 1256403600
-
1
tz.transition 2010, 3, :o3, 1269709200
-
1
tz.transition 2010, 10, :o2, 1288458000
-
1
tz.transition 2011, 3, :o5, 1301158800
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Yekaterinburg
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Yekaterinburg' do |tz|
-
1
tz.offset :o0, 14544, 0, :LMT
-
1
tz.offset :o1, 14400, 0, :SVET
-
1
tz.offset :o2, 18000, 0, :SVET
-
1
tz.offset :o3, 18000, 3600, :SVEST
-
1
tz.offset :o4, 14400, 3600, :SVEST
-
1
tz.offset :o5, 18000, 0, :YEKT
-
1
tz.offset :o6, 18000, 3600, :YEKST
-
1
tz.offset :o7, 21600, 0, :YEKT
-
-
1
tz.transition 1919, 7, :o1, 1453292699, 600
-
1
tz.transition 1930, 6, :o2, 7278445, 3
-
1
tz.transition 1981, 3, :o3, 354913200
-
1
tz.transition 1981, 9, :o2, 370720800
-
1
tz.transition 1982, 3, :o3, 386449200
-
1
tz.transition 1982, 9, :o2, 402256800
-
1
tz.transition 1983, 3, :o3, 417985200
-
1
tz.transition 1983, 9, :o2, 433792800
-
1
tz.transition 1984, 3, :o3, 449607600
-
1
tz.transition 1984, 9, :o2, 465339600
-
1
tz.transition 1985, 3, :o3, 481064400
-
1
tz.transition 1985, 9, :o2, 496789200
-
1
tz.transition 1986, 3, :o3, 512514000
-
1
tz.transition 1986, 9, :o2, 528238800
-
1
tz.transition 1987, 3, :o3, 543963600
-
1
tz.transition 1987, 9, :o2, 559688400
-
1
tz.transition 1988, 3, :o3, 575413200
-
1
tz.transition 1988, 9, :o2, 591138000
-
1
tz.transition 1989, 3, :o3, 606862800
-
1
tz.transition 1989, 9, :o2, 622587600
-
1
tz.transition 1990, 3, :o3, 638312400
-
1
tz.transition 1990, 9, :o2, 654642000
-
1
tz.transition 1991, 3, :o4, 670366800
-
1
tz.transition 1991, 9, :o1, 686095200
-
1
tz.transition 1992, 1, :o5, 695772000
-
1
tz.transition 1992, 3, :o6, 701805600
-
1
tz.transition 1992, 9, :o5, 717526800
-
1
tz.transition 1993, 3, :o6, 733266000
-
1
tz.transition 1993, 9, :o5, 748990800
-
1
tz.transition 1994, 3, :o6, 764715600
-
1
tz.transition 1994, 9, :o5, 780440400
-
1
tz.transition 1995, 3, :o6, 796165200
-
1
tz.transition 1995, 9, :o5, 811890000
-
1
tz.transition 1996, 3, :o6, 828219600
-
1
tz.transition 1996, 10, :o5, 846363600
-
1
tz.transition 1997, 3, :o6, 859669200
-
1
tz.transition 1997, 10, :o5, 877813200
-
1
tz.transition 1998, 3, :o6, 891118800
-
1
tz.transition 1998, 10, :o5, 909262800
-
1
tz.transition 1999, 3, :o6, 922568400
-
1
tz.transition 1999, 10, :o5, 941317200
-
1
tz.transition 2000, 3, :o6, 954018000
-
1
tz.transition 2000, 10, :o5, 972766800
-
1
tz.transition 2001, 3, :o6, 985467600
-
1
tz.transition 2001, 10, :o5, 1004216400
-
1
tz.transition 2002, 3, :o6, 1017522000
-
1
tz.transition 2002, 10, :o5, 1035666000
-
1
tz.transition 2003, 3, :o6, 1048971600
-
1
tz.transition 2003, 10, :o5, 1067115600
-
1
tz.transition 2004, 3, :o6, 1080421200
-
1
tz.transition 2004, 10, :o5, 1099170000
-
1
tz.transition 2005, 3, :o6, 1111870800
-
1
tz.transition 2005, 10, :o5, 1130619600
-
1
tz.transition 2006, 3, :o6, 1143320400
-
1
tz.transition 2006, 10, :o5, 1162069200
-
1
tz.transition 2007, 3, :o6, 1174770000
-
1
tz.transition 2007, 10, :o5, 1193518800
-
1
tz.transition 2008, 3, :o6, 1206824400
-
1
tz.transition 2008, 10, :o5, 1224968400
-
1
tz.transition 2009, 3, :o6, 1238274000
-
1
tz.transition 2009, 10, :o5, 1256418000
-
1
tz.transition 2010, 3, :o6, 1269723600
-
1
tz.transition 2010, 10, :o5, 1288472400
-
1
tz.transition 2011, 3, :o7, 1301173200
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Asia
-
1
module Yerevan
-
1
include TimezoneDefinition
-
-
1
timezone 'Asia/Yerevan' do |tz|
-
1
tz.offset :o0, 10680, 0, :LMT
-
1
tz.offset :o1, 10800, 0, :YERT
-
1
tz.offset :o2, 14400, 0, :YERT
-
1
tz.offset :o3, 14400, 3600, :YERST
-
1
tz.offset :o4, 10800, 3600, :YERST
-
1
tz.offset :o5, 10800, 3600, :AMST
-
1
tz.offset :o6, 10800, 0, :AMT
-
1
tz.offset :o7, 14400, 0, :AMT
-
1
tz.offset :o8, 14400, 3600, :AMST
-
-
1
tz.transition 1924, 5, :o1, 1745213311, 720
-
1
tz.transition 1957, 2, :o2, 19487187, 8
-
1
tz.transition 1981, 3, :o3, 354916800
-
1
tz.transition 1981, 9, :o2, 370724400
-
1
tz.transition 1982, 3, :o3, 386452800
-
1
tz.transition 1982, 9, :o2, 402260400
-
1
tz.transition 1983, 3, :o3, 417988800
-
1
tz.transition 1983, 9, :o2, 433796400
-
1
tz.transition 1984, 3, :o3, 449611200
-
1
tz.transition 1984, 9, :o2, 465343200
-
1
tz.transition 1985, 3, :o3, 481068000
-
1
tz.transition 1985, 9, :o2, 496792800
-
1
tz.transition 1986, 3, :o3, 512517600
-
1
tz.transition 1986, 9, :o2, 528242400
-
1
tz.transition 1987, 3, :o3, 543967200
-
1
tz.transition 1987, 9, :o2, 559692000
-
1
tz.transition 1988, 3, :o3, 575416800
-
1
tz.transition 1988, 9, :o2, 591141600
-
1
tz.transition 1989, 3, :o3, 606866400
-
1
tz.transition 1989, 9, :o2, 622591200
-
1
tz.transition 1990, 3, :o3, 638316000
-
1
tz.transition 1990, 9, :o2, 654645600
-
1
tz.transition 1991, 3, :o4, 670370400
-
1
tz.transition 1991, 9, :o5, 685569600
-
1
tz.transition 1991, 9, :o6, 686098800
-
1
tz.transition 1992, 3, :o5, 701812800
-
1
tz.transition 1992, 9, :o6, 717534000
-
1
tz.transition 1993, 3, :o5, 733273200
-
1
tz.transition 1993, 9, :o6, 748998000
-
1
tz.transition 1994, 3, :o5, 764722800
-
1
tz.transition 1994, 9, :o6, 780447600
-
1
tz.transition 1995, 3, :o5, 796172400
-
1
tz.transition 1995, 9, :o7, 811897200
-
1
tz.transition 1997, 3, :o8, 859672800
-
1
tz.transition 1997, 10, :o7, 877816800
-
1
tz.transition 1998, 3, :o8, 891122400
-
1
tz.transition 1998, 10, :o7, 909266400
-
1
tz.transition 1999, 3, :o8, 922572000
-
1
tz.transition 1999, 10, :o7, 941320800
-
1
tz.transition 2000, 3, :o8, 954021600
-
1
tz.transition 2000, 10, :o7, 972770400
-
1
tz.transition 2001, 3, :o8, 985471200
-
1
tz.transition 2001, 10, :o7, 1004220000
-
1
tz.transition 2002, 3, :o8, 1017525600
-
1
tz.transition 2002, 10, :o7, 1035669600
-
1
tz.transition 2003, 3, :o8, 1048975200
-
1
tz.transition 2003, 10, :o7, 1067119200
-
1
tz.transition 2004, 3, :o8, 1080424800
-
1
tz.transition 2004, 10, :o7, 1099173600
-
1
tz.transition 2005, 3, :o8, 1111874400
-
1
tz.transition 2005, 10, :o7, 1130623200
-
1
tz.transition 2006, 3, :o8, 1143324000
-
1
tz.transition 2006, 10, :o7, 1162072800
-
1
tz.transition 2007, 3, :o8, 1174773600
-
1
tz.transition 2007, 10, :o7, 1193522400
-
1
tz.transition 2008, 3, :o8, 1206828000
-
1
tz.transition 2008, 10, :o7, 1224972000
-
1
tz.transition 2009, 3, :o8, 1238277600
-
1
tz.transition 2009, 10, :o7, 1256421600
-
1
tz.transition 2010, 3, :o8, 1269727200
-
1
tz.transition 2010, 10, :o7, 1288476000
-
1
tz.transition 2011, 3, :o8, 1301176800
-
1
tz.transition 2011, 10, :o7, 1319925600
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Atlantic
-
1
module Azores
-
1
include TimezoneDefinition
-
-
1
timezone 'Atlantic/Azores' do |tz|
-
1
tz.offset :o0, -6160, 0, :LMT
-
1
tz.offset :o1, -6872, 0, :HMT
-
1
tz.offset :o2, -7200, 0, :AZOT
-
1
tz.offset :o3, -7200, 3600, :AZOST
-
1
tz.offset :o4, -7200, 7200, :AZOMT
-
1
tz.offset :o5, -3600, 0, :AZOT
-
1
tz.offset :o6, -3600, 3600, :AZOST
-
1
tz.offset :o7, 0, 0, :WET
-
-
1
tz.transition 1884, 1, :o1, 2601910697, 1080
-
1
tz.transition 1911, 5, :o2, 26127150259, 10800
-
1
tz.transition 1916, 6, :o3, 58104781, 24
-
1
tz.transition 1916, 11, :o2, 29054023, 12
-
1
tz.transition 1917, 3, :o3, 58110925, 24
-
1
tz.transition 1917, 10, :o2, 58116397, 24
-
1
tz.transition 1918, 3, :o3, 58119709, 24
-
1
tz.transition 1918, 10, :o2, 58125157, 24
-
1
tz.transition 1919, 3, :o3, 58128445, 24
-
1
tz.transition 1919, 10, :o2, 58133917, 24
-
1
tz.transition 1920, 3, :o3, 58137229, 24
-
1
tz.transition 1920, 10, :o2, 58142701, 24
-
1
tz.transition 1921, 3, :o3, 58145989, 24
-
1
tz.transition 1921, 10, :o2, 58151461, 24
-
1
tz.transition 1924, 4, :o3, 58173421, 24
-
1
tz.transition 1924, 10, :o2, 58177765, 24
-
1
tz.transition 1926, 4, :o3, 58190965, 24
-
1
tz.transition 1926, 10, :o2, 58194997, 24
-
1
tz.transition 1927, 4, :o3, 58199533, 24
-
1
tz.transition 1927, 10, :o2, 58203733, 24
-
1
tz.transition 1928, 4, :o3, 58208437, 24
-
1
tz.transition 1928, 10, :o2, 58212637, 24
-
1
tz.transition 1929, 4, :o3, 58217341, 24
-
1
tz.transition 1929, 10, :o2, 58221373, 24
-
1
tz.transition 1931, 4, :o3, 58234813, 24
-
1
tz.transition 1931, 10, :o2, 58238845, 24
-
1
tz.transition 1932, 4, :o3, 58243213, 24
-
1
tz.transition 1932, 10, :o2, 58247581, 24
-
1
tz.transition 1934, 4, :o3, 58260853, 24
-
1
tz.transition 1934, 10, :o2, 58265221, 24
-
1
tz.transition 1935, 3, :o3, 58269421, 24
-
1
tz.transition 1935, 10, :o2, 58273957, 24
-
1
tz.transition 1936, 4, :o3, 58278661, 24
-
1
tz.transition 1936, 10, :o2, 58282693, 24
-
1
tz.transition 1937, 4, :o3, 58287061, 24
-
1
tz.transition 1937, 10, :o2, 58291429, 24
-
1
tz.transition 1938, 3, :o3, 58295629, 24
-
1
tz.transition 1938, 10, :o2, 58300165, 24
-
1
tz.transition 1939, 4, :o3, 58304869, 24
-
1
tz.transition 1939, 11, :o2, 58310077, 24
-
1
tz.transition 1940, 2, :o3, 58312429, 24
-
1
tz.transition 1940, 10, :o2, 58317805, 24
-
1
tz.transition 1941, 4, :o3, 58322173, 24
-
1
tz.transition 1941, 10, :o2, 58326565, 24
-
1
tz.transition 1942, 3, :o3, 58330405, 24
-
1
tz.transition 1942, 4, :o4, 4860951, 2
-
1
tz.transition 1942, 8, :o3, 4861175, 2
-
1
tz.transition 1942, 10, :o2, 58335781, 24
-
1
tz.transition 1943, 3, :o3, 58339141, 24
-
1
tz.transition 1943, 4, :o4, 4861665, 2
-
1
tz.transition 1943, 8, :o3, 4861931, 2
-
1
tz.transition 1943, 10, :o2, 58344685, 24
-
1
tz.transition 1944, 3, :o3, 58347877, 24
-
1
tz.transition 1944, 4, :o4, 4862407, 2
-
1
tz.transition 1944, 8, :o3, 4862659, 2
-
1
tz.transition 1944, 10, :o2, 58353421, 24
-
1
tz.transition 1945, 3, :o3, 58356613, 24
-
1
tz.transition 1945, 4, :o4, 4863135, 2
-
1
tz.transition 1945, 8, :o3, 4863387, 2
-
1
tz.transition 1945, 10, :o2, 58362157, 24
-
1
tz.transition 1946, 4, :o3, 58366021, 24
-
1
tz.transition 1946, 10, :o2, 58370389, 24
-
1
tz.transition 1947, 4, :o3, 7296845, 3
-
1
tz.transition 1947, 10, :o2, 7297391, 3
-
1
tz.transition 1948, 4, :o3, 7297937, 3
-
1
tz.transition 1948, 10, :o2, 7298483, 3
-
1
tz.transition 1949, 4, :o3, 7299029, 3
-
1
tz.transition 1949, 10, :o2, 7299575, 3
-
1
tz.transition 1951, 4, :o3, 7301213, 3
-
1
tz.transition 1951, 10, :o2, 7301780, 3
-
1
tz.transition 1952, 4, :o3, 7302326, 3
-
1
tz.transition 1952, 10, :o2, 7302872, 3
-
1
tz.transition 1953, 4, :o3, 7303418, 3
-
1
tz.transition 1953, 10, :o2, 7303964, 3
-
1
tz.transition 1954, 4, :o3, 7304510, 3
-
1
tz.transition 1954, 10, :o2, 7305056, 3
-
1
tz.transition 1955, 4, :o3, 7305602, 3
-
1
tz.transition 1955, 10, :o2, 7306148, 3
-
1
tz.transition 1956, 4, :o3, 7306694, 3
-
1
tz.transition 1956, 10, :o2, 7307261, 3
-
1
tz.transition 1957, 4, :o3, 7307807, 3
-
1
tz.transition 1957, 10, :o2, 7308353, 3
-
1
tz.transition 1958, 4, :o3, 7308899, 3
-
1
tz.transition 1958, 10, :o2, 7309445, 3
-
1
tz.transition 1959, 4, :o3, 7309991, 3
-
1
tz.transition 1959, 10, :o2, 7310537, 3
-
1
tz.transition 1960, 4, :o3, 7311083, 3
-
1
tz.transition 1960, 10, :o2, 7311629, 3
-
1
tz.transition 1961, 4, :o3, 7312175, 3
-
1
tz.transition 1961, 10, :o2, 7312721, 3
-
1
tz.transition 1962, 4, :o3, 7313267, 3
-
1
tz.transition 1962, 10, :o2, 7313834, 3
-
1
tz.transition 1963, 4, :o3, 7314380, 3
-
1
tz.transition 1963, 10, :o2, 7314926, 3
-
1
tz.transition 1964, 4, :o3, 7315472, 3
-
1
tz.transition 1964, 10, :o2, 7316018, 3
-
1
tz.transition 1965, 4, :o3, 7316564, 3
-
1
tz.transition 1965, 10, :o2, 7317110, 3
-
1
tz.transition 1966, 4, :o5, 7317656, 3
-
1
tz.transition 1977, 3, :o6, 228272400
-
1
tz.transition 1977, 9, :o5, 243997200
-
1
tz.transition 1978, 4, :o6, 260326800
-
1
tz.transition 1978, 10, :o5, 276051600
-
1
tz.transition 1979, 4, :o6, 291776400
-
1
tz.transition 1979, 9, :o5, 307504800
-
1
tz.transition 1980, 3, :o6, 323226000
-
1
tz.transition 1980, 9, :o5, 338954400
-
1
tz.transition 1981, 3, :o6, 354679200
-
1
tz.transition 1981, 9, :o5, 370404000
-
1
tz.transition 1982, 3, :o6, 386128800
-
1
tz.transition 1982, 9, :o5, 401853600
-
1
tz.transition 1983, 3, :o6, 417582000
-
1
tz.transition 1983, 9, :o5, 433303200
-
1
tz.transition 1984, 3, :o6, 449028000
-
1
tz.transition 1984, 9, :o5, 465357600
-
1
tz.transition 1985, 3, :o6, 481082400
-
1
tz.transition 1985, 9, :o5, 496807200
-
1
tz.transition 1986, 3, :o6, 512532000
-
1
tz.transition 1986, 9, :o5, 528256800
-
1
tz.transition 1987, 3, :o6, 543981600
-
1
tz.transition 1987, 9, :o5, 559706400
-
1
tz.transition 1988, 3, :o6, 575431200
-
1
tz.transition 1988, 9, :o5, 591156000
-
1
tz.transition 1989, 3, :o6, 606880800
-
1
tz.transition 1989, 9, :o5, 622605600
-
1
tz.transition 1990, 3, :o6, 638330400
-
1
tz.transition 1990, 9, :o5, 654660000
-
1
tz.transition 1991, 3, :o6, 670384800
-
1
tz.transition 1991, 9, :o5, 686109600
-
1
tz.transition 1992, 3, :o6, 701834400
-
1
tz.transition 1992, 9, :o7, 717559200
-
1
tz.transition 1993, 3, :o6, 733280400
-
1
tz.transition 1993, 9, :o5, 749005200
-
1
tz.transition 1994, 3, :o6, 764730000
-
1
tz.transition 1994, 9, :o5, 780454800
-
1
tz.transition 1995, 3, :o6, 796179600
-
1
tz.transition 1995, 9, :o5, 811904400
-
1
tz.transition 1996, 3, :o6, 828234000
-
1
tz.transition 1996, 10, :o5, 846378000
-
1
tz.transition 1997, 3, :o6, 859683600
-
1
tz.transition 1997, 10, :o5, 877827600
-
1
tz.transition 1998, 3, :o6, 891133200
-
1
tz.transition 1998, 10, :o5, 909277200
-
1
tz.transition 1999, 3, :o6, 922582800
-
1
tz.transition 1999, 10, :o5, 941331600
-
1
tz.transition 2000, 3, :o6, 954032400
-
1
tz.transition 2000, 10, :o5, 972781200
-
1
tz.transition 2001, 3, :o6, 985482000
-
1
tz.transition 2001, 10, :o5, 1004230800
-
1
tz.transition 2002, 3, :o6, 1017536400
-
1
tz.transition 2002, 10, :o5, 1035680400
-
1
tz.transition 2003, 3, :o6, 1048986000
-
1
tz.transition 2003, 10, :o5, 1067130000
-
1
tz.transition 2004, 3, :o6, 1080435600
-
1
tz.transition 2004, 10, :o5, 1099184400
-
1
tz.transition 2005, 3, :o6, 1111885200
-
1
tz.transition 2005, 10, :o5, 1130634000
-
1
tz.transition 2006, 3, :o6, 1143334800
-
1
tz.transition 2006, 10, :o5, 1162083600
-
1
tz.transition 2007, 3, :o6, 1174784400
-
1
tz.transition 2007, 10, :o5, 1193533200
-
1
tz.transition 2008, 3, :o6, 1206838800
-
1
tz.transition 2008, 10, :o5, 1224982800
-
1
tz.transition 2009, 3, :o6, 1238288400
-
1
tz.transition 2009, 10, :o5, 1256432400
-
1
tz.transition 2010, 3, :o6, 1269738000
-
1
tz.transition 2010, 10, :o5, 1288486800
-
1
tz.transition 2011, 3, :o6, 1301187600
-
1
tz.transition 2011, 10, :o5, 1319936400
-
1
tz.transition 2012, 3, :o6, 1332637200
-
1
tz.transition 2012, 10, :o5, 1351386000
-
1
tz.transition 2013, 3, :o6, 1364691600
-
1
tz.transition 2013, 10, :o5, 1382835600
-
1
tz.transition 2014, 3, :o6, 1396141200
-
1
tz.transition 2014, 10, :o5, 1414285200
-
1
tz.transition 2015, 3, :o6, 1427590800
-
1
tz.transition 2015, 10, :o5, 1445734800
-
1
tz.transition 2016, 3, :o6, 1459040400
-
1
tz.transition 2016, 10, :o5, 1477789200
-
1
tz.transition 2017, 3, :o6, 1490490000
-
1
tz.transition 2017, 10, :o5, 1509238800
-
1
tz.transition 2018, 3, :o6, 1521939600
-
1
tz.transition 2018, 10, :o5, 1540688400
-
1
tz.transition 2019, 3, :o6, 1553994000
-
1
tz.transition 2019, 10, :o5, 1572138000
-
1
tz.transition 2020, 3, :o6, 1585443600
-
1
tz.transition 2020, 10, :o5, 1603587600
-
1
tz.transition 2021, 3, :o6, 1616893200
-
1
tz.transition 2021, 10, :o5, 1635642000
-
1
tz.transition 2022, 3, :o6, 1648342800
-
1
tz.transition 2022, 10, :o5, 1667091600
-
1
tz.transition 2023, 3, :o6, 1679792400
-
1
tz.transition 2023, 10, :o5, 1698541200
-
1
tz.transition 2024, 3, :o6, 1711846800
-
1
tz.transition 2024, 10, :o5, 1729990800
-
1
tz.transition 2025, 3, :o6, 1743296400
-
1
tz.transition 2025, 10, :o5, 1761440400
-
1
tz.transition 2026, 3, :o6, 1774746000
-
1
tz.transition 2026, 10, :o5, 1792890000
-
1
tz.transition 2027, 3, :o6, 1806195600
-
1
tz.transition 2027, 10, :o5, 1824944400
-
1
tz.transition 2028, 3, :o6, 1837645200
-
1
tz.transition 2028, 10, :o5, 1856394000
-
1
tz.transition 2029, 3, :o6, 1869094800
-
1
tz.transition 2029, 10, :o5, 1887843600
-
1
tz.transition 2030, 3, :o6, 1901149200
-
1
tz.transition 2030, 10, :o5, 1919293200
-
1
tz.transition 2031, 3, :o6, 1932598800
-
1
tz.transition 2031, 10, :o5, 1950742800
-
1
tz.transition 2032, 3, :o6, 1964048400
-
1
tz.transition 2032, 10, :o5, 1982797200
-
1
tz.transition 2033, 3, :o6, 1995498000
-
1
tz.transition 2033, 10, :o5, 2014246800
-
1
tz.transition 2034, 3, :o6, 2026947600
-
1
tz.transition 2034, 10, :o5, 2045696400
-
1
tz.transition 2035, 3, :o6, 2058397200
-
1
tz.transition 2035, 10, :o5, 2077146000
-
1
tz.transition 2036, 3, :o6, 2090451600
-
1
tz.transition 2036, 10, :o5, 2108595600
-
1
tz.transition 2037, 3, :o6, 2121901200
-
1
tz.transition 2037, 10, :o5, 2140045200
-
1
tz.transition 2038, 3, :o6, 59172253, 24
-
1
tz.transition 2038, 10, :o5, 59177461, 24
-
1
tz.transition 2039, 3, :o6, 59180989, 24
-
1
tz.transition 2039, 10, :o5, 59186197, 24
-
1
tz.transition 2040, 3, :o6, 59189725, 24
-
1
tz.transition 2040, 10, :o5, 59194933, 24
-
1
tz.transition 2041, 3, :o6, 59198629, 24
-
1
tz.transition 2041, 10, :o5, 59203669, 24
-
1
tz.transition 2042, 3, :o6, 59207365, 24
-
1
tz.transition 2042, 10, :o5, 59212405, 24
-
1
tz.transition 2043, 3, :o6, 59216101, 24
-
1
tz.transition 2043, 10, :o5, 59221141, 24
-
1
tz.transition 2044, 3, :o6, 59224837, 24
-
1
tz.transition 2044, 10, :o5, 59230045, 24
-
1
tz.transition 2045, 3, :o6, 59233573, 24
-
1
tz.transition 2045, 10, :o5, 59238781, 24
-
1
tz.transition 2046, 3, :o6, 59242309, 24
-
1
tz.transition 2046, 10, :o5, 59247517, 24
-
1
tz.transition 2047, 3, :o6, 59251213, 24
-
1
tz.transition 2047, 10, :o5, 59256253, 24
-
1
tz.transition 2048, 3, :o6, 59259949, 24
-
1
tz.transition 2048, 10, :o5, 59264989, 24
-
1
tz.transition 2049, 3, :o6, 59268685, 24
-
1
tz.transition 2049, 10, :o5, 59273893, 24
-
1
tz.transition 2050, 3, :o6, 59277421, 24
-
1
tz.transition 2050, 10, :o5, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Atlantic
-
1
module Cape_Verde
-
1
include TimezoneDefinition
-
-
1
timezone 'Atlantic/Cape_Verde' do |tz|
-
1
tz.offset :o0, -5644, 0, :LMT
-
1
tz.offset :o1, -7200, 0, :CVT
-
1
tz.offset :o2, -7200, 3600, :CVST
-
1
tz.offset :o3, -3600, 0, :CVT
-
-
1
tz.transition 1907, 1, :o1, 52219653811, 21600
-
1
tz.transition 1942, 9, :o2, 29167243, 12
-
1
tz.transition 1945, 10, :o1, 58361845, 24
-
1
tz.transition 1975, 11, :o3, 186120000
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Atlantic
-
1
module South_Georgia
-
1
include TimezoneDefinition
-
-
1
timezone 'Atlantic/South_Georgia' do |tz|
-
1
tz.offset :o0, -8768, 0, :LMT
-
1
tz.offset :o1, -7200, 0, :GST
-
-
1
tz.transition 1890, 1, :o1, 1627673806, 675
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Australia
-
1
module Adelaide
-
1
include TimezoneDefinition
-
-
1
timezone 'Australia/Adelaide' do |tz|
-
1
tz.offset :o0, 33260, 0, :LMT
-
1
tz.offset :o1, 32400, 0, :CST
-
1
tz.offset :o2, 34200, 0, :CST
-
1
tz.offset :o3, 34200, 3600, :CST
-
-
1
tz.transition 1895, 1, :o1, 10425132497, 4320
-
1
tz.transition 1899, 4, :o2, 19318201, 8
-
1
tz.transition 1916, 12, :o3, 3486569911, 1440
-
1
tz.transition 1917, 3, :o2, 116222983, 48
-
1
tz.transition 1941, 12, :o3, 38885763, 16
-
1
tz.transition 1942, 3, :o2, 116661463, 48
-
1
tz.transition 1942, 9, :o3, 38890067, 16
-
1
tz.transition 1943, 3, :o2, 116678935, 48
-
1
tz.transition 1943, 10, :o3, 38896003, 16
-
1
tz.transition 1944, 3, :o2, 116696407, 48
-
1
tz.transition 1971, 10, :o3, 57688200
-
1
tz.transition 1972, 2, :o2, 67969800
-
1
tz.transition 1972, 10, :o3, 89137800
-
1
tz.transition 1973, 3, :o2, 100024200
-
1
tz.transition 1973, 10, :o3, 120587400
-
1
tz.transition 1974, 3, :o2, 131473800
-
1
tz.transition 1974, 10, :o3, 152037000
-
1
tz.transition 1975, 3, :o2, 162923400
-
1
tz.transition 1975, 10, :o3, 183486600
-
1
tz.transition 1976, 3, :o2, 194977800
-
1
tz.transition 1976, 10, :o3, 215541000
-
1
tz.transition 1977, 3, :o2, 226427400
-
1
tz.transition 1977, 10, :o3, 246990600
-
1
tz.transition 1978, 3, :o2, 257877000
-
1
tz.transition 1978, 10, :o3, 278440200
-
1
tz.transition 1979, 3, :o2, 289326600
-
1
tz.transition 1979, 10, :o3, 309889800
-
1
tz.transition 1980, 3, :o2, 320776200
-
1
tz.transition 1980, 10, :o3, 341339400
-
1
tz.transition 1981, 2, :o2, 352225800
-
1
tz.transition 1981, 10, :o3, 372789000
-
1
tz.transition 1982, 3, :o2, 384280200
-
1
tz.transition 1982, 10, :o3, 404843400
-
1
tz.transition 1983, 3, :o2, 415729800
-
1
tz.transition 1983, 10, :o3, 436293000
-
1
tz.transition 1984, 3, :o2, 447179400
-
1
tz.transition 1984, 10, :o3, 467742600
-
1
tz.transition 1985, 3, :o2, 478629000
-
1
tz.transition 1985, 10, :o3, 499192200
-
1
tz.transition 1986, 3, :o2, 511288200
-
1
tz.transition 1986, 10, :o3, 530037000
-
1
tz.transition 1987, 3, :o2, 542737800
-
1
tz.transition 1987, 10, :o3, 562091400
-
1
tz.transition 1988, 3, :o2, 574792200
-
1
tz.transition 1988, 10, :o3, 594145800
-
1
tz.transition 1989, 3, :o2, 606241800
-
1
tz.transition 1989, 10, :o3, 625595400
-
1
tz.transition 1990, 3, :o2, 637691400
-
1
tz.transition 1990, 10, :o3, 657045000
-
1
tz.transition 1991, 3, :o2, 667931400
-
1
tz.transition 1991, 10, :o3, 688494600
-
1
tz.transition 1992, 3, :o2, 701195400
-
1
tz.transition 1992, 10, :o3, 719944200
-
1
tz.transition 1993, 3, :o2, 731435400
-
1
tz.transition 1993, 10, :o3, 751998600
-
1
tz.transition 1994, 3, :o2, 764094600
-
1
tz.transition 1994, 10, :o3, 783448200
-
1
tz.transition 1995, 3, :o2, 796149000
-
1
tz.transition 1995, 10, :o3, 814897800
-
1
tz.transition 1996, 3, :o2, 828203400
-
1
tz.transition 1996, 10, :o3, 846347400
-
1
tz.transition 1997, 3, :o2, 859653000
-
1
tz.transition 1997, 10, :o3, 877797000
-
1
tz.transition 1998, 3, :o2, 891102600
-
1
tz.transition 1998, 10, :o3, 909246600
-
1
tz.transition 1999, 3, :o2, 922552200
-
1
tz.transition 1999, 10, :o3, 941301000
-
1
tz.transition 2000, 3, :o2, 954001800
-
1
tz.transition 2000, 10, :o3, 972750600
-
1
tz.transition 2001, 3, :o2, 985451400
-
1
tz.transition 2001, 10, :o3, 1004200200
-
1
tz.transition 2002, 3, :o2, 1017505800
-
1
tz.transition 2002, 10, :o3, 1035649800
-
1
tz.transition 2003, 3, :o2, 1048955400
-
1
tz.transition 2003, 10, :o3, 1067099400
-
1
tz.transition 2004, 3, :o2, 1080405000
-
1
tz.transition 2004, 10, :o3, 1099153800
-
1
tz.transition 2005, 3, :o2, 1111854600
-
1
tz.transition 2005, 10, :o3, 1130603400
-
1
tz.transition 2006, 4, :o2, 1143909000
-
1
tz.transition 2006, 10, :o3, 1162053000
-
1
tz.transition 2007, 3, :o2, 1174753800
-
1
tz.transition 2007, 10, :o3, 1193502600
-
1
tz.transition 2008, 4, :o2, 1207413000
-
1
tz.transition 2008, 10, :o3, 1223137800
-
1
tz.transition 2009, 4, :o2, 1238862600
-
1
tz.transition 2009, 10, :o3, 1254587400
-
1
tz.transition 2010, 4, :o2, 1270312200
-
1
tz.transition 2010, 10, :o3, 1286037000
-
1
tz.transition 2011, 4, :o2, 1301761800
-
1
tz.transition 2011, 10, :o3, 1317486600
-
1
tz.transition 2012, 3, :o2, 1333211400
-
1
tz.transition 2012, 10, :o3, 1349541000
-
1
tz.transition 2013, 4, :o2, 1365265800
-
1
tz.transition 2013, 10, :o3, 1380990600
-
1
tz.transition 2014, 4, :o2, 1396715400
-
1
tz.transition 2014, 10, :o3, 1412440200
-
1
tz.transition 2015, 4, :o2, 1428165000
-
1
tz.transition 2015, 10, :o3, 1443889800
-
1
tz.transition 2016, 4, :o2, 1459614600
-
1
tz.transition 2016, 10, :o3, 1475339400
-
1
tz.transition 2017, 4, :o2, 1491064200
-
1
tz.transition 2017, 9, :o3, 1506789000
-
1
tz.transition 2018, 3, :o2, 1522513800
-
1
tz.transition 2018, 10, :o3, 1538843400
-
1
tz.transition 2019, 4, :o2, 1554568200
-
1
tz.transition 2019, 10, :o3, 1570293000
-
1
tz.transition 2020, 4, :o2, 1586017800
-
1
tz.transition 2020, 10, :o3, 1601742600
-
1
tz.transition 2021, 4, :o2, 1617467400
-
1
tz.transition 2021, 10, :o3, 1633192200
-
1
tz.transition 2022, 4, :o2, 1648917000
-
1
tz.transition 2022, 10, :o3, 1664641800
-
1
tz.transition 2023, 4, :o2, 1680366600
-
1
tz.transition 2023, 9, :o3, 1696091400
-
1
tz.transition 2024, 4, :o2, 1712421000
-
1
tz.transition 2024, 10, :o3, 1728145800
-
1
tz.transition 2025, 4, :o2, 1743870600
-
1
tz.transition 2025, 10, :o3, 1759595400
-
1
tz.transition 2026, 4, :o2, 1775320200
-
1
tz.transition 2026, 10, :o3, 1791045000
-
1
tz.transition 2027, 4, :o2, 1806769800
-
1
tz.transition 2027, 10, :o3, 1822494600
-
1
tz.transition 2028, 4, :o2, 1838219400
-
1
tz.transition 2028, 9, :o3, 1853944200
-
1
tz.transition 2029, 3, :o2, 1869669000
-
1
tz.transition 2029, 10, :o3, 1885998600
-
1
tz.transition 2030, 4, :o2, 1901723400
-
1
tz.transition 2030, 10, :o3, 1917448200
-
1
tz.transition 2031, 4, :o2, 1933173000
-
1
tz.transition 2031, 10, :o3, 1948897800
-
1
tz.transition 2032, 4, :o2, 1964622600
-
1
tz.transition 2032, 10, :o3, 1980347400
-
1
tz.transition 2033, 4, :o2, 1996072200
-
1
tz.transition 2033, 10, :o3, 2011797000
-
1
tz.transition 2034, 4, :o2, 2027521800
-
1
tz.transition 2034, 9, :o3, 2043246600
-
1
tz.transition 2035, 3, :o2, 2058971400
-
1
tz.transition 2035, 10, :o3, 2075301000
-
1
tz.transition 2036, 4, :o2, 2091025800
-
1
tz.transition 2036, 10, :o3, 2106750600
-
1
tz.transition 2037, 4, :o2, 2122475400
-
1
tz.transition 2037, 10, :o3, 2138200200
-
1
tz.transition 2038, 4, :o2, 39448275, 16
-
1
tz.transition 2038, 10, :o3, 39451187, 16
-
1
tz.transition 2039, 4, :o2, 39454099, 16
-
1
tz.transition 2039, 10, :o3, 39457011, 16
-
1
tz.transition 2040, 3, :o2, 39459923, 16
-
1
tz.transition 2040, 10, :o3, 39462947, 16
-
1
tz.transition 2041, 4, :o2, 39465859, 16
-
1
tz.transition 2041, 10, :o3, 39468771, 16
-
1
tz.transition 2042, 4, :o2, 39471683, 16
-
1
tz.transition 2042, 10, :o3, 39474595, 16
-
1
tz.transition 2043, 4, :o2, 39477507, 16
-
1
tz.transition 2043, 10, :o3, 39480419, 16
-
1
tz.transition 2044, 4, :o2, 39483331, 16
-
1
tz.transition 2044, 10, :o3, 39486243, 16
-
1
tz.transition 2045, 4, :o2, 39489155, 16
-
1
tz.transition 2045, 9, :o3, 39492067, 16
-
1
tz.transition 2046, 3, :o2, 39494979, 16
-
1
tz.transition 2046, 10, :o3, 39498003, 16
-
1
tz.transition 2047, 4, :o2, 39500915, 16
-
1
tz.transition 2047, 10, :o3, 39503827, 16
-
1
tz.transition 2048, 4, :o2, 39506739, 16
-
1
tz.transition 2048, 10, :o3, 39509651, 16
-
1
tz.transition 2049, 4, :o2, 39512563, 16
-
1
tz.transition 2049, 10, :o3, 39515475, 16
-
1
tz.transition 2050, 4, :o2, 39518387, 16
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Australia
-
1
module Brisbane
-
1
include TimezoneDefinition
-
-
1
timezone 'Australia/Brisbane' do |tz|
-
1
tz.offset :o0, 36728, 0, :LMT
-
1
tz.offset :o1, 36000, 0, :EST
-
1
tz.offset :o2, 36000, 3600, :EST
-
-
1
tz.transition 1894, 12, :o1, 26062496009, 10800
-
1
tz.transition 1916, 12, :o2, 3486569881, 1440
-
1
tz.transition 1917, 3, :o1, 19370497, 8
-
1
tz.transition 1941, 12, :o2, 14582161, 6
-
1
tz.transition 1942, 3, :o1, 19443577, 8
-
1
tz.transition 1942, 9, :o2, 14583775, 6
-
1
tz.transition 1943, 3, :o1, 19446489, 8
-
1
tz.transition 1943, 10, :o2, 14586001, 6
-
1
tz.transition 1944, 3, :o1, 19449401, 8
-
1
tz.transition 1971, 10, :o2, 57686400
-
1
tz.transition 1972, 2, :o1, 67968000
-
1
tz.transition 1989, 10, :o2, 625593600
-
1
tz.transition 1990, 3, :o1, 636480000
-
1
tz.transition 1990, 10, :o2, 657043200
-
1
tz.transition 1991, 3, :o1, 667929600
-
1
tz.transition 1991, 10, :o2, 688492800
-
1
tz.transition 1992, 2, :o1, 699379200
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Australia
-
1
module Darwin
-
1
include TimezoneDefinition
-
-
1
timezone 'Australia/Darwin' do |tz|
-
1
tz.offset :o0, 31400, 0, :LMT
-
1
tz.offset :o1, 32400, 0, :CST
-
1
tz.offset :o2, 34200, 0, :CST
-
1
tz.offset :o3, 34200, 3600, :CST
-
-
1
tz.transition 1895, 1, :o1, 1042513259, 432
-
1
tz.transition 1899, 4, :o2, 19318201, 8
-
1
tz.transition 1916, 12, :o3, 3486569911, 1440
-
1
tz.transition 1917, 3, :o2, 116222983, 48
-
1
tz.transition 1941, 12, :o3, 38885763, 16
-
1
tz.transition 1942, 3, :o2, 116661463, 48
-
1
tz.transition 1942, 9, :o3, 38890067, 16
-
1
tz.transition 1943, 3, :o2, 116678935, 48
-
1
tz.transition 1943, 10, :o3, 38896003, 16
-
1
tz.transition 1944, 3, :o2, 116696407, 48
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Australia
-
1
module Hobart
-
1
include TimezoneDefinition
-
-
1
timezone 'Australia/Hobart' do |tz|
-
1
tz.offset :o0, 35356, 0, :LMT
-
1
tz.offset :o1, 36000, 0, :EST
-
1
tz.offset :o2, 36000, 3600, :EST
-
-
1
tz.transition 1895, 8, :o1, 52130241161, 21600
-
1
tz.transition 1916, 9, :o2, 14526823, 6
-
1
tz.transition 1917, 3, :o1, 19370497, 8
-
1
tz.transition 1941, 12, :o2, 14582161, 6
-
1
tz.transition 1942, 3, :o1, 19443577, 8
-
1
tz.transition 1942, 9, :o2, 14583775, 6
-
1
tz.transition 1943, 3, :o1, 19446489, 8
-
1
tz.transition 1943, 10, :o2, 14586001, 6
-
1
tz.transition 1944, 3, :o1, 19449401, 8
-
1
tz.transition 1967, 9, :o2, 14638585, 6
-
1
tz.transition 1968, 3, :o1, 14639677, 6
-
1
tz.transition 1968, 10, :o2, 14640937, 6
-
1
tz.transition 1969, 3, :o1, 14641735, 6
-
1
tz.transition 1969, 10, :o2, 14643121, 6
-
1
tz.transition 1970, 3, :o1, 5673600
-
1
tz.transition 1970, 10, :o2, 25632000
-
1
tz.transition 1971, 3, :o1, 37728000
-
1
tz.transition 1971, 10, :o2, 57686400
-
1
tz.transition 1972, 2, :o1, 67968000
-
1
tz.transition 1972, 10, :o2, 89136000
-
1
tz.transition 1973, 3, :o1, 100022400
-
1
tz.transition 1973, 10, :o2, 120585600
-
1
tz.transition 1974, 3, :o1, 131472000
-
1
tz.transition 1974, 10, :o2, 152035200
-
1
tz.transition 1975, 3, :o1, 162921600
-
1
tz.transition 1975, 10, :o2, 183484800
-
1
tz.transition 1976, 3, :o1, 194976000
-
1
tz.transition 1976, 10, :o2, 215539200
-
1
tz.transition 1977, 3, :o1, 226425600
-
1
tz.transition 1977, 10, :o2, 246988800
-
1
tz.transition 1978, 3, :o1, 257875200
-
1
tz.transition 1978, 10, :o2, 278438400
-
1
tz.transition 1979, 3, :o1, 289324800
-
1
tz.transition 1979, 10, :o2, 309888000
-
1
tz.transition 1980, 3, :o1, 320774400
-
1
tz.transition 1980, 10, :o2, 341337600
-
1
tz.transition 1981, 2, :o1, 352224000
-
1
tz.transition 1981, 10, :o2, 372787200
-
1
tz.transition 1982, 3, :o1, 386092800
-
1
tz.transition 1982, 10, :o2, 404841600
-
1
tz.transition 1983, 3, :o1, 417542400
-
1
tz.transition 1983, 10, :o2, 436291200
-
1
tz.transition 1984, 3, :o1, 447177600
-
1
tz.transition 1984, 10, :o2, 467740800
-
1
tz.transition 1985, 3, :o1, 478627200
-
1
tz.transition 1985, 10, :o2, 499190400
-
1
tz.transition 1986, 3, :o1, 510076800
-
1
tz.transition 1986, 10, :o2, 530035200
-
1
tz.transition 1987, 3, :o1, 542736000
-
1
tz.transition 1987, 10, :o2, 562089600
-
1
tz.transition 1988, 3, :o1, 574790400
-
1
tz.transition 1988, 10, :o2, 594144000
-
1
tz.transition 1989, 3, :o1, 606240000
-
1
tz.transition 1989, 10, :o2, 625593600
-
1
tz.transition 1990, 3, :o1, 637689600
-
1
tz.transition 1990, 10, :o2, 657043200
-
1
tz.transition 1991, 3, :o1, 670348800
-
1
tz.transition 1991, 10, :o2, 686678400
-
1
tz.transition 1992, 3, :o1, 701798400
-
1
tz.transition 1992, 10, :o2, 718128000
-
1
tz.transition 1993, 3, :o1, 733248000
-
1
tz.transition 1993, 10, :o2, 749577600
-
1
tz.transition 1994, 3, :o1, 764697600
-
1
tz.transition 1994, 10, :o2, 781027200
-
1
tz.transition 1995, 3, :o1, 796147200
-
1
tz.transition 1995, 9, :o2, 812476800
-
1
tz.transition 1996, 3, :o1, 828201600
-
1
tz.transition 1996, 10, :o2, 844531200
-
1
tz.transition 1997, 3, :o1, 859651200
-
1
tz.transition 1997, 10, :o2, 875980800
-
1
tz.transition 1998, 3, :o1, 891100800
-
1
tz.transition 1998, 10, :o2, 907430400
-
1
tz.transition 1999, 3, :o1, 922550400
-
1
tz.transition 1999, 10, :o2, 938880000
-
1
tz.transition 2000, 3, :o1, 954000000
-
1
tz.transition 2000, 8, :o2, 967305600
-
1
tz.transition 2001, 3, :o1, 985449600
-
1
tz.transition 2001, 10, :o2, 1002384000
-
1
tz.transition 2002, 3, :o1, 1017504000
-
1
tz.transition 2002, 10, :o2, 1033833600
-
1
tz.transition 2003, 3, :o1, 1048953600
-
1
tz.transition 2003, 10, :o2, 1065283200
-
1
tz.transition 2004, 3, :o1, 1080403200
-
1
tz.transition 2004, 10, :o2, 1096732800
-
1
tz.transition 2005, 3, :o1, 1111852800
-
1
tz.transition 2005, 10, :o2, 1128182400
-
1
tz.transition 2006, 4, :o1, 1143907200
-
1
tz.transition 2006, 9, :o2, 1159632000
-
1
tz.transition 2007, 3, :o1, 1174752000
-
1
tz.transition 2007, 10, :o2, 1191686400
-
1
tz.transition 2008, 4, :o1, 1207411200
-
1
tz.transition 2008, 10, :o2, 1223136000
-
1
tz.transition 2009, 4, :o1, 1238860800
-
1
tz.transition 2009, 10, :o2, 1254585600
-
1
tz.transition 2010, 4, :o1, 1270310400
-
1
tz.transition 2010, 10, :o2, 1286035200
-
1
tz.transition 2011, 4, :o1, 1301760000
-
1
tz.transition 2011, 10, :o2, 1317484800
-
1
tz.transition 2012, 3, :o1, 1333209600
-
1
tz.transition 2012, 10, :o2, 1349539200
-
1
tz.transition 2013, 4, :o1, 1365264000
-
1
tz.transition 2013, 10, :o2, 1380988800
-
1
tz.transition 2014, 4, :o1, 1396713600
-
1
tz.transition 2014, 10, :o2, 1412438400
-
1
tz.transition 2015, 4, :o1, 1428163200
-
1
tz.transition 2015, 10, :o2, 1443888000
-
1
tz.transition 2016, 4, :o1, 1459612800
-
1
tz.transition 2016, 10, :o2, 1475337600
-
1
tz.transition 2017, 4, :o1, 1491062400
-
1
tz.transition 2017, 9, :o2, 1506787200
-
1
tz.transition 2018, 3, :o1, 1522512000
-
1
tz.transition 2018, 10, :o2, 1538841600
-
1
tz.transition 2019, 4, :o1, 1554566400
-
1
tz.transition 2019, 10, :o2, 1570291200
-
1
tz.transition 2020, 4, :o1, 1586016000
-
1
tz.transition 2020, 10, :o2, 1601740800
-
1
tz.transition 2021, 4, :o1, 1617465600
-
1
tz.transition 2021, 10, :o2, 1633190400
-
1
tz.transition 2022, 4, :o1, 1648915200
-
1
tz.transition 2022, 10, :o2, 1664640000
-
1
tz.transition 2023, 4, :o1, 1680364800
-
1
tz.transition 2023, 9, :o2, 1696089600
-
1
tz.transition 2024, 4, :o1, 1712419200
-
1
tz.transition 2024, 10, :o2, 1728144000
-
1
tz.transition 2025, 4, :o1, 1743868800
-
1
tz.transition 2025, 10, :o2, 1759593600
-
1
tz.transition 2026, 4, :o1, 1775318400
-
1
tz.transition 2026, 10, :o2, 1791043200
-
1
tz.transition 2027, 4, :o1, 1806768000
-
1
tz.transition 2027, 10, :o2, 1822492800
-
1
tz.transition 2028, 4, :o1, 1838217600
-
1
tz.transition 2028, 9, :o2, 1853942400
-
1
tz.transition 2029, 3, :o1, 1869667200
-
1
tz.transition 2029, 10, :o2, 1885996800
-
1
tz.transition 2030, 4, :o1, 1901721600
-
1
tz.transition 2030, 10, :o2, 1917446400
-
1
tz.transition 2031, 4, :o1, 1933171200
-
1
tz.transition 2031, 10, :o2, 1948896000
-
1
tz.transition 2032, 4, :o1, 1964620800
-
1
tz.transition 2032, 10, :o2, 1980345600
-
1
tz.transition 2033, 4, :o1, 1996070400
-
1
tz.transition 2033, 10, :o2, 2011795200
-
1
tz.transition 2034, 4, :o1, 2027520000
-
1
tz.transition 2034, 9, :o2, 2043244800
-
1
tz.transition 2035, 3, :o1, 2058969600
-
1
tz.transition 2035, 10, :o2, 2075299200
-
1
tz.transition 2036, 4, :o1, 2091024000
-
1
tz.transition 2036, 10, :o2, 2106748800
-
1
tz.transition 2037, 4, :o1, 2122473600
-
1
tz.transition 2037, 10, :o2, 2138198400
-
1
tz.transition 2038, 4, :o1, 14793103, 6
-
1
tz.transition 2038, 10, :o2, 14794195, 6
-
1
tz.transition 2039, 4, :o1, 14795287, 6
-
1
tz.transition 2039, 10, :o2, 14796379, 6
-
1
tz.transition 2040, 3, :o1, 14797471, 6
-
1
tz.transition 2040, 10, :o2, 14798605, 6
-
1
tz.transition 2041, 4, :o1, 14799697, 6
-
1
tz.transition 2041, 10, :o2, 14800789, 6
-
1
tz.transition 2042, 4, :o1, 14801881, 6
-
1
tz.transition 2042, 10, :o2, 14802973, 6
-
1
tz.transition 2043, 4, :o1, 14804065, 6
-
1
tz.transition 2043, 10, :o2, 14805157, 6
-
1
tz.transition 2044, 4, :o1, 14806249, 6
-
1
tz.transition 2044, 10, :o2, 14807341, 6
-
1
tz.transition 2045, 4, :o1, 14808433, 6
-
1
tz.transition 2045, 9, :o2, 14809525, 6
-
1
tz.transition 2046, 3, :o1, 14810617, 6
-
1
tz.transition 2046, 10, :o2, 14811751, 6
-
1
tz.transition 2047, 4, :o1, 14812843, 6
-
1
tz.transition 2047, 10, :o2, 14813935, 6
-
1
tz.transition 2048, 4, :o1, 14815027, 6
-
1
tz.transition 2048, 10, :o2, 14816119, 6
-
1
tz.transition 2049, 4, :o1, 14817211, 6
-
1
tz.transition 2049, 10, :o2, 14818303, 6
-
1
tz.transition 2050, 4, :o1, 14819395, 6
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Australia
-
1
module Melbourne
-
1
include TimezoneDefinition
-
-
1
timezone 'Australia/Melbourne' do |tz|
-
1
tz.offset :o0, 34792, 0, :LMT
-
1
tz.offset :o1, 36000, 0, :EST
-
1
tz.offset :o2, 36000, 3600, :EST
-
-
1
tz.transition 1895, 1, :o1, 26062831051, 10800
-
1
tz.transition 1916, 12, :o2, 3486569881, 1440
-
1
tz.transition 1917, 3, :o1, 19370497, 8
-
1
tz.transition 1941, 12, :o2, 14582161, 6
-
1
tz.transition 1942, 3, :o1, 19443577, 8
-
1
tz.transition 1942, 9, :o2, 14583775, 6
-
1
tz.transition 1943, 3, :o1, 19446489, 8
-
1
tz.transition 1943, 10, :o2, 14586001, 6
-
1
tz.transition 1944, 3, :o1, 19449401, 8
-
1
tz.transition 1971, 10, :o2, 57686400
-
1
tz.transition 1972, 2, :o1, 67968000
-
1
tz.transition 1972, 10, :o2, 89136000
-
1
tz.transition 1973, 3, :o1, 100022400
-
1
tz.transition 1973, 10, :o2, 120585600
-
1
tz.transition 1974, 3, :o1, 131472000
-
1
tz.transition 1974, 10, :o2, 152035200
-
1
tz.transition 1975, 3, :o1, 162921600
-
1
tz.transition 1975, 10, :o2, 183484800
-
1
tz.transition 1976, 3, :o1, 194976000
-
1
tz.transition 1976, 10, :o2, 215539200
-
1
tz.transition 1977, 3, :o1, 226425600
-
1
tz.transition 1977, 10, :o2, 246988800
-
1
tz.transition 1978, 3, :o1, 257875200
-
1
tz.transition 1978, 10, :o2, 278438400
-
1
tz.transition 1979, 3, :o1, 289324800
-
1
tz.transition 1979, 10, :o2, 309888000
-
1
tz.transition 1980, 3, :o1, 320774400
-
1
tz.transition 1980, 10, :o2, 341337600
-
1
tz.transition 1981, 2, :o1, 352224000
-
1
tz.transition 1981, 10, :o2, 372787200
-
1
tz.transition 1982, 3, :o1, 384278400
-
1
tz.transition 1982, 10, :o2, 404841600
-
1
tz.transition 1983, 3, :o1, 415728000
-
1
tz.transition 1983, 10, :o2, 436291200
-
1
tz.transition 1984, 3, :o1, 447177600
-
1
tz.transition 1984, 10, :o2, 467740800
-
1
tz.transition 1985, 3, :o1, 478627200
-
1
tz.transition 1985, 10, :o2, 499190400
-
1
tz.transition 1986, 3, :o1, 511286400
-
1
tz.transition 1986, 10, :o2, 530035200
-
1
tz.transition 1987, 3, :o1, 542736000
-
1
tz.transition 1987, 10, :o2, 561484800
-
1
tz.transition 1988, 3, :o1, 574790400
-
1
tz.transition 1988, 10, :o2, 594144000
-
1
tz.transition 1989, 3, :o1, 606240000
-
1
tz.transition 1989, 10, :o2, 625593600
-
1
tz.transition 1990, 3, :o1, 637689600
-
1
tz.transition 1990, 10, :o2, 657043200
-
1
tz.transition 1991, 3, :o1, 667929600
-
1
tz.transition 1991, 10, :o2, 688492800
-
1
tz.transition 1992, 2, :o1, 699379200
-
1
tz.transition 1992, 10, :o2, 719942400
-
1
tz.transition 1993, 3, :o1, 731433600
-
1
tz.transition 1993, 10, :o2, 751996800
-
1
tz.transition 1994, 3, :o1, 762883200
-
1
tz.transition 1994, 10, :o2, 783446400
-
1
tz.transition 1995, 3, :o1, 796147200
-
1
tz.transition 1995, 10, :o2, 814896000
-
1
tz.transition 1996, 3, :o1, 828201600
-
1
tz.transition 1996, 10, :o2, 846345600
-
1
tz.transition 1997, 3, :o1, 859651200
-
1
tz.transition 1997, 10, :o2, 877795200
-
1
tz.transition 1998, 3, :o1, 891100800
-
1
tz.transition 1998, 10, :o2, 909244800
-
1
tz.transition 1999, 3, :o1, 922550400
-
1
tz.transition 1999, 10, :o2, 941299200
-
1
tz.transition 2000, 3, :o1, 954000000
-
1
tz.transition 2000, 8, :o2, 967305600
-
1
tz.transition 2001, 3, :o1, 985449600
-
1
tz.transition 2001, 10, :o2, 1004198400
-
1
tz.transition 2002, 3, :o1, 1017504000
-
1
tz.transition 2002, 10, :o2, 1035648000
-
1
tz.transition 2003, 3, :o1, 1048953600
-
1
tz.transition 2003, 10, :o2, 1067097600
-
1
tz.transition 2004, 3, :o1, 1080403200
-
1
tz.transition 2004, 10, :o2, 1099152000
-
1
tz.transition 2005, 3, :o1, 1111852800
-
1
tz.transition 2005, 10, :o2, 1130601600
-
1
tz.transition 2006, 4, :o1, 1143907200
-
1
tz.transition 2006, 10, :o2, 1162051200
-
1
tz.transition 2007, 3, :o1, 1174752000
-
1
tz.transition 2007, 10, :o2, 1193500800
-
1
tz.transition 2008, 4, :o1, 1207411200
-
1
tz.transition 2008, 10, :o2, 1223136000
-
1
tz.transition 2009, 4, :o1, 1238860800
-
1
tz.transition 2009, 10, :o2, 1254585600
-
1
tz.transition 2010, 4, :o1, 1270310400
-
1
tz.transition 2010, 10, :o2, 1286035200
-
1
tz.transition 2011, 4, :o1, 1301760000
-
1
tz.transition 2011, 10, :o2, 1317484800
-
1
tz.transition 2012, 3, :o1, 1333209600
-
1
tz.transition 2012, 10, :o2, 1349539200
-
1
tz.transition 2013, 4, :o1, 1365264000
-
1
tz.transition 2013, 10, :o2, 1380988800
-
1
tz.transition 2014, 4, :o1, 1396713600
-
1
tz.transition 2014, 10, :o2, 1412438400
-
1
tz.transition 2015, 4, :o1, 1428163200
-
1
tz.transition 2015, 10, :o2, 1443888000
-
1
tz.transition 2016, 4, :o1, 1459612800
-
1
tz.transition 2016, 10, :o2, 1475337600
-
1
tz.transition 2017, 4, :o1, 1491062400
-
1
tz.transition 2017, 9, :o2, 1506787200
-
1
tz.transition 2018, 3, :o1, 1522512000
-
1
tz.transition 2018, 10, :o2, 1538841600
-
1
tz.transition 2019, 4, :o1, 1554566400
-
1
tz.transition 2019, 10, :o2, 1570291200
-
1
tz.transition 2020, 4, :o1, 1586016000
-
1
tz.transition 2020, 10, :o2, 1601740800
-
1
tz.transition 2021, 4, :o1, 1617465600
-
1
tz.transition 2021, 10, :o2, 1633190400
-
1
tz.transition 2022, 4, :o1, 1648915200
-
1
tz.transition 2022, 10, :o2, 1664640000
-
1
tz.transition 2023, 4, :o1, 1680364800
-
1
tz.transition 2023, 9, :o2, 1696089600
-
1
tz.transition 2024, 4, :o1, 1712419200
-
1
tz.transition 2024, 10, :o2, 1728144000
-
1
tz.transition 2025, 4, :o1, 1743868800
-
1
tz.transition 2025, 10, :o2, 1759593600
-
1
tz.transition 2026, 4, :o1, 1775318400
-
1
tz.transition 2026, 10, :o2, 1791043200
-
1
tz.transition 2027, 4, :o1, 1806768000
-
1
tz.transition 2027, 10, :o2, 1822492800
-
1
tz.transition 2028, 4, :o1, 1838217600
-
1
tz.transition 2028, 9, :o2, 1853942400
-
1
tz.transition 2029, 3, :o1, 1869667200
-
1
tz.transition 2029, 10, :o2, 1885996800
-
1
tz.transition 2030, 4, :o1, 1901721600
-
1
tz.transition 2030, 10, :o2, 1917446400
-
1
tz.transition 2031, 4, :o1, 1933171200
-
1
tz.transition 2031, 10, :o2, 1948896000
-
1
tz.transition 2032, 4, :o1, 1964620800
-
1
tz.transition 2032, 10, :o2, 1980345600
-
1
tz.transition 2033, 4, :o1, 1996070400
-
1
tz.transition 2033, 10, :o2, 2011795200
-
1
tz.transition 2034, 4, :o1, 2027520000
-
1
tz.transition 2034, 9, :o2, 2043244800
-
1
tz.transition 2035, 3, :o1, 2058969600
-
1
tz.transition 2035, 10, :o2, 2075299200
-
1
tz.transition 2036, 4, :o1, 2091024000
-
1
tz.transition 2036, 10, :o2, 2106748800
-
1
tz.transition 2037, 4, :o1, 2122473600
-
1
tz.transition 2037, 10, :o2, 2138198400
-
1
tz.transition 2038, 4, :o1, 14793103, 6
-
1
tz.transition 2038, 10, :o2, 14794195, 6
-
1
tz.transition 2039, 4, :o1, 14795287, 6
-
1
tz.transition 2039, 10, :o2, 14796379, 6
-
1
tz.transition 2040, 3, :o1, 14797471, 6
-
1
tz.transition 2040, 10, :o2, 14798605, 6
-
1
tz.transition 2041, 4, :o1, 14799697, 6
-
1
tz.transition 2041, 10, :o2, 14800789, 6
-
1
tz.transition 2042, 4, :o1, 14801881, 6
-
1
tz.transition 2042, 10, :o2, 14802973, 6
-
1
tz.transition 2043, 4, :o1, 14804065, 6
-
1
tz.transition 2043, 10, :o2, 14805157, 6
-
1
tz.transition 2044, 4, :o1, 14806249, 6
-
1
tz.transition 2044, 10, :o2, 14807341, 6
-
1
tz.transition 2045, 4, :o1, 14808433, 6
-
1
tz.transition 2045, 9, :o2, 14809525, 6
-
1
tz.transition 2046, 3, :o1, 14810617, 6
-
1
tz.transition 2046, 10, :o2, 14811751, 6
-
1
tz.transition 2047, 4, :o1, 14812843, 6
-
1
tz.transition 2047, 10, :o2, 14813935, 6
-
1
tz.transition 2048, 4, :o1, 14815027, 6
-
1
tz.transition 2048, 10, :o2, 14816119, 6
-
1
tz.transition 2049, 4, :o1, 14817211, 6
-
1
tz.transition 2049, 10, :o2, 14818303, 6
-
1
tz.transition 2050, 4, :o1, 14819395, 6
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Australia
-
1
module Perth
-
1
include TimezoneDefinition
-
-
1
timezone 'Australia/Perth' do |tz|
-
1
tz.offset :o0, 27804, 0, :LMT
-
1
tz.offset :o1, 28800, 0, :WST
-
1
tz.offset :o2, 28800, 3600, :WST
-
-
1
tz.transition 1895, 11, :o1, 17377402883, 7200
-
1
tz.transition 1916, 12, :o2, 3486570001, 1440
-
1
tz.transition 1917, 3, :o1, 58111493, 24
-
1
tz.transition 1941, 12, :o2, 9721441, 4
-
1
tz.transition 1942, 3, :o1, 58330733, 24
-
1
tz.transition 1942, 9, :o2, 9722517, 4
-
1
tz.transition 1943, 3, :o1, 58339469, 24
-
1
tz.transition 1974, 10, :o2, 152042400
-
1
tz.transition 1975, 3, :o1, 162928800
-
1
tz.transition 1983, 10, :o2, 436298400
-
1
tz.transition 1984, 3, :o1, 447184800
-
1
tz.transition 1991, 11, :o2, 690314400
-
1
tz.transition 1992, 2, :o1, 699386400
-
1
tz.transition 2006, 12, :o2, 1165082400
-
1
tz.transition 2007, 3, :o1, 1174759200
-
1
tz.transition 2007, 10, :o2, 1193508000
-
1
tz.transition 2008, 3, :o1, 1206813600
-
1
tz.transition 2008, 10, :o2, 1224957600
-
1
tz.transition 2009, 3, :o1, 1238263200
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Australia
-
1
module Sydney
-
1
include TimezoneDefinition
-
-
1
timezone 'Australia/Sydney' do |tz|
-
1
tz.offset :o0, 36292, 0, :LMT
-
1
tz.offset :o1, 36000, 0, :EST
-
1
tz.offset :o2, 36000, 3600, :EST
-
-
1
tz.transition 1895, 1, :o1, 52125661727, 21600
-
1
tz.transition 1916, 12, :o2, 3486569881, 1440
-
1
tz.transition 1917, 3, :o1, 19370497, 8
-
1
tz.transition 1941, 12, :o2, 14582161, 6
-
1
tz.transition 1942, 3, :o1, 19443577, 8
-
1
tz.transition 1942, 9, :o2, 14583775, 6
-
1
tz.transition 1943, 3, :o1, 19446489, 8
-
1
tz.transition 1943, 10, :o2, 14586001, 6
-
1
tz.transition 1944, 3, :o1, 19449401, 8
-
1
tz.transition 1971, 10, :o2, 57686400
-
1
tz.transition 1972, 2, :o1, 67968000
-
1
tz.transition 1972, 10, :o2, 89136000
-
1
tz.transition 1973, 3, :o1, 100022400
-
1
tz.transition 1973, 10, :o2, 120585600
-
1
tz.transition 1974, 3, :o1, 131472000
-
1
tz.transition 1974, 10, :o2, 152035200
-
1
tz.transition 1975, 3, :o1, 162921600
-
1
tz.transition 1975, 10, :o2, 183484800
-
1
tz.transition 1976, 3, :o1, 194976000
-
1
tz.transition 1976, 10, :o2, 215539200
-
1
tz.transition 1977, 3, :o1, 226425600
-
1
tz.transition 1977, 10, :o2, 246988800
-
1
tz.transition 1978, 3, :o1, 257875200
-
1
tz.transition 1978, 10, :o2, 278438400
-
1
tz.transition 1979, 3, :o1, 289324800
-
1
tz.transition 1979, 10, :o2, 309888000
-
1
tz.transition 1980, 3, :o1, 320774400
-
1
tz.transition 1980, 10, :o2, 341337600
-
1
tz.transition 1981, 2, :o1, 352224000
-
1
tz.transition 1981, 10, :o2, 372787200
-
1
tz.transition 1982, 4, :o1, 386697600
-
1
tz.transition 1982, 10, :o2, 404841600
-
1
tz.transition 1983, 3, :o1, 415728000
-
1
tz.transition 1983, 10, :o2, 436291200
-
1
tz.transition 1984, 3, :o1, 447177600
-
1
tz.transition 1984, 10, :o2, 467740800
-
1
tz.transition 1985, 3, :o1, 478627200
-
1
tz.transition 1985, 10, :o2, 499190400
-
1
tz.transition 1986, 3, :o1, 511286400
-
1
tz.transition 1986, 10, :o2, 530035200
-
1
tz.transition 1987, 3, :o1, 542736000
-
1
tz.transition 1987, 10, :o2, 562089600
-
1
tz.transition 1988, 3, :o1, 574790400
-
1
tz.transition 1988, 10, :o2, 594144000
-
1
tz.transition 1989, 3, :o1, 606240000
-
1
tz.transition 1989, 10, :o2, 625593600
-
1
tz.transition 1990, 3, :o1, 636480000
-
1
tz.transition 1990, 10, :o2, 657043200
-
1
tz.transition 1991, 3, :o1, 667929600
-
1
tz.transition 1991, 10, :o2, 688492800
-
1
tz.transition 1992, 2, :o1, 699379200
-
1
tz.transition 1992, 10, :o2, 719942400
-
1
tz.transition 1993, 3, :o1, 731433600
-
1
tz.transition 1993, 10, :o2, 751996800
-
1
tz.transition 1994, 3, :o1, 762883200
-
1
tz.transition 1994, 10, :o2, 783446400
-
1
tz.transition 1995, 3, :o1, 794332800
-
1
tz.transition 1995, 10, :o2, 814896000
-
1
tz.transition 1996, 3, :o1, 828201600
-
1
tz.transition 1996, 10, :o2, 846345600
-
1
tz.transition 1997, 3, :o1, 859651200
-
1
tz.transition 1997, 10, :o2, 877795200
-
1
tz.transition 1998, 3, :o1, 891100800
-
1
tz.transition 1998, 10, :o2, 909244800
-
1
tz.transition 1999, 3, :o1, 922550400
-
1
tz.transition 1999, 10, :o2, 941299200
-
1
tz.transition 2000, 3, :o1, 954000000
-
1
tz.transition 2000, 8, :o2, 967305600
-
1
tz.transition 2001, 3, :o1, 985449600
-
1
tz.transition 2001, 10, :o2, 1004198400
-
1
tz.transition 2002, 3, :o1, 1017504000
-
1
tz.transition 2002, 10, :o2, 1035648000
-
1
tz.transition 2003, 3, :o1, 1048953600
-
1
tz.transition 2003, 10, :o2, 1067097600
-
1
tz.transition 2004, 3, :o1, 1080403200
-
1
tz.transition 2004, 10, :o2, 1099152000
-
1
tz.transition 2005, 3, :o1, 1111852800
-
1
tz.transition 2005, 10, :o2, 1130601600
-
1
tz.transition 2006, 4, :o1, 1143907200
-
1
tz.transition 2006, 10, :o2, 1162051200
-
1
tz.transition 2007, 3, :o1, 1174752000
-
1
tz.transition 2007, 10, :o2, 1193500800
-
1
tz.transition 2008, 4, :o1, 1207411200
-
1
tz.transition 2008, 10, :o2, 1223136000
-
1
tz.transition 2009, 4, :o1, 1238860800
-
1
tz.transition 2009, 10, :o2, 1254585600
-
1
tz.transition 2010, 4, :o1, 1270310400
-
1
tz.transition 2010, 10, :o2, 1286035200
-
1
tz.transition 2011, 4, :o1, 1301760000
-
1
tz.transition 2011, 10, :o2, 1317484800
-
1
tz.transition 2012, 3, :o1, 1333209600
-
1
tz.transition 2012, 10, :o2, 1349539200
-
1
tz.transition 2013, 4, :o1, 1365264000
-
1
tz.transition 2013, 10, :o2, 1380988800
-
1
tz.transition 2014, 4, :o1, 1396713600
-
1
tz.transition 2014, 10, :o2, 1412438400
-
1
tz.transition 2015, 4, :o1, 1428163200
-
1
tz.transition 2015, 10, :o2, 1443888000
-
1
tz.transition 2016, 4, :o1, 1459612800
-
1
tz.transition 2016, 10, :o2, 1475337600
-
1
tz.transition 2017, 4, :o1, 1491062400
-
1
tz.transition 2017, 9, :o2, 1506787200
-
1
tz.transition 2018, 3, :o1, 1522512000
-
1
tz.transition 2018, 10, :o2, 1538841600
-
1
tz.transition 2019, 4, :o1, 1554566400
-
1
tz.transition 2019, 10, :o2, 1570291200
-
1
tz.transition 2020, 4, :o1, 1586016000
-
1
tz.transition 2020, 10, :o2, 1601740800
-
1
tz.transition 2021, 4, :o1, 1617465600
-
1
tz.transition 2021, 10, :o2, 1633190400
-
1
tz.transition 2022, 4, :o1, 1648915200
-
1
tz.transition 2022, 10, :o2, 1664640000
-
1
tz.transition 2023, 4, :o1, 1680364800
-
1
tz.transition 2023, 9, :o2, 1696089600
-
1
tz.transition 2024, 4, :o1, 1712419200
-
1
tz.transition 2024, 10, :o2, 1728144000
-
1
tz.transition 2025, 4, :o1, 1743868800
-
1
tz.transition 2025, 10, :o2, 1759593600
-
1
tz.transition 2026, 4, :o1, 1775318400
-
1
tz.transition 2026, 10, :o2, 1791043200
-
1
tz.transition 2027, 4, :o1, 1806768000
-
1
tz.transition 2027, 10, :o2, 1822492800
-
1
tz.transition 2028, 4, :o1, 1838217600
-
1
tz.transition 2028, 9, :o2, 1853942400
-
1
tz.transition 2029, 3, :o1, 1869667200
-
1
tz.transition 2029, 10, :o2, 1885996800
-
1
tz.transition 2030, 4, :o1, 1901721600
-
1
tz.transition 2030, 10, :o2, 1917446400
-
1
tz.transition 2031, 4, :o1, 1933171200
-
1
tz.transition 2031, 10, :o2, 1948896000
-
1
tz.transition 2032, 4, :o1, 1964620800
-
1
tz.transition 2032, 10, :o2, 1980345600
-
1
tz.transition 2033, 4, :o1, 1996070400
-
1
tz.transition 2033, 10, :o2, 2011795200
-
1
tz.transition 2034, 4, :o1, 2027520000
-
1
tz.transition 2034, 9, :o2, 2043244800
-
1
tz.transition 2035, 3, :o1, 2058969600
-
1
tz.transition 2035, 10, :o2, 2075299200
-
1
tz.transition 2036, 4, :o1, 2091024000
-
1
tz.transition 2036, 10, :o2, 2106748800
-
1
tz.transition 2037, 4, :o1, 2122473600
-
1
tz.transition 2037, 10, :o2, 2138198400
-
1
tz.transition 2038, 4, :o1, 14793103, 6
-
1
tz.transition 2038, 10, :o2, 14794195, 6
-
1
tz.transition 2039, 4, :o1, 14795287, 6
-
1
tz.transition 2039, 10, :o2, 14796379, 6
-
1
tz.transition 2040, 3, :o1, 14797471, 6
-
1
tz.transition 2040, 10, :o2, 14798605, 6
-
1
tz.transition 2041, 4, :o1, 14799697, 6
-
1
tz.transition 2041, 10, :o2, 14800789, 6
-
1
tz.transition 2042, 4, :o1, 14801881, 6
-
1
tz.transition 2042, 10, :o2, 14802973, 6
-
1
tz.transition 2043, 4, :o1, 14804065, 6
-
1
tz.transition 2043, 10, :o2, 14805157, 6
-
1
tz.transition 2044, 4, :o1, 14806249, 6
-
1
tz.transition 2044, 10, :o2, 14807341, 6
-
1
tz.transition 2045, 4, :o1, 14808433, 6
-
1
tz.transition 2045, 9, :o2, 14809525, 6
-
1
tz.transition 2046, 3, :o1, 14810617, 6
-
1
tz.transition 2046, 10, :o2, 14811751, 6
-
1
tz.transition 2047, 4, :o1, 14812843, 6
-
1
tz.transition 2047, 10, :o2, 14813935, 6
-
1
tz.transition 2048, 4, :o1, 14815027, 6
-
1
tz.transition 2048, 10, :o2, 14816119, 6
-
1
tz.transition 2049, 4, :o1, 14817211, 6
-
1
tz.transition 2049, 10, :o2, 14818303, 6
-
1
tz.transition 2050, 4, :o1, 14819395, 6
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Etc
-
1
module UTC
-
1
include TimezoneDefinition
-
-
1
timezone 'Etc/UTC' do |tz|
-
1
tz.offset :o0, 0, 0, :UTC
-
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Amsterdam
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Amsterdam' do |tz|
-
1
tz.offset :o0, 1172, 0, :LMT
-
1
tz.offset :o1, 1172, 0, :AMT
-
1
tz.offset :o2, 1172, 3600, :NST
-
1
tz.offset :o3, 1200, 3600, :NEST
-
1
tz.offset :o4, 1200, 0, :NET
-
1
tz.offset :o5, 3600, 3600, :CEST
-
1
tz.offset :o6, 3600, 0, :CET
-
-
1
tz.transition 1834, 12, :o1, 51651636907, 21600
-
1
tz.transition 1916, 4, :o2, 52293264907, 21600
-
1
tz.transition 1916, 9, :o1, 52296568807, 21600
-
1
tz.transition 1917, 4, :o2, 52300826707, 21600
-
1
tz.transition 1917, 9, :o1, 52304153107, 21600
-
1
tz.transition 1918, 4, :o2, 52308386707, 21600
-
1
tz.transition 1918, 9, :o1, 52312317907, 21600
-
1
tz.transition 1919, 4, :o2, 52316400307, 21600
-
1
tz.transition 1919, 9, :o1, 52320180307, 21600
-
1
tz.transition 1920, 4, :o2, 52324262707, 21600
-
1
tz.transition 1920, 9, :o1, 52328042707, 21600
-
1
tz.transition 1921, 4, :o2, 52332125107, 21600
-
1
tz.transition 1921, 9, :o1, 52335905107, 21600
-
1
tz.transition 1922, 3, :o2, 52339814707, 21600
-
1
tz.transition 1922, 10, :o1, 52344048307, 21600
-
1
tz.transition 1923, 6, :o2, 52349145907, 21600
-
1
tz.transition 1923, 10, :o1, 52351910707, 21600
-
1
tz.transition 1924, 3, :o2, 52355690707, 21600
-
1
tz.transition 1924, 10, :o1, 52359773107, 21600
-
1
tz.transition 1925, 6, :o2, 52365021907, 21600
-
1
tz.transition 1925, 10, :o1, 52367635507, 21600
-
1
tz.transition 1926, 5, :o2, 52372452307, 21600
-
1
tz.transition 1926, 10, :o1, 52375497907, 21600
-
1
tz.transition 1927, 5, :o2, 52380336307, 21600
-
1
tz.transition 1927, 10, :o1, 52383360307, 21600
-
1
tz.transition 1928, 5, :o2, 52388241907, 21600
-
1
tz.transition 1928, 10, :o1, 52391373907, 21600
-
1
tz.transition 1929, 5, :o2, 52396125907, 21600
-
1
tz.transition 1929, 10, :o1, 52399236307, 21600
-
1
tz.transition 1930, 5, :o2, 52404009907, 21600
-
1
tz.transition 1930, 10, :o1, 52407098707, 21600
-
1
tz.transition 1931, 5, :o2, 52411893907, 21600
-
1
tz.transition 1931, 10, :o1, 52414961107, 21600
-
1
tz.transition 1932, 5, :o2, 52419950707, 21600
-
1
tz.transition 1932, 10, :o1, 52422823507, 21600
-
1
tz.transition 1933, 5, :o2, 52427683507, 21600
-
1
tz.transition 1933, 10, :o1, 52430837107, 21600
-
1
tz.transition 1934, 5, :o2, 52435567507, 21600
-
1
tz.transition 1934, 10, :o1, 52438699507, 21600
-
1
tz.transition 1935, 5, :o2, 52443451507, 21600
-
1
tz.transition 1935, 10, :o1, 52446561907, 21600
-
1
tz.transition 1936, 5, :o2, 52451357107, 21600
-
1
tz.transition 1936, 10, :o1, 52454424307, 21600
-
1
tz.transition 1937, 5, :o2, 52459392307, 21600
-
1
tz.transition 1937, 6, :o3, 52460253607, 21600
-
1
tz.transition 1937, 10, :o4, 174874289, 72
-
1
tz.transition 1938, 5, :o3, 174890417, 72
-
1
tz.transition 1938, 10, :o4, 174900497, 72
-
1
tz.transition 1939, 5, :o3, 174916697, 72
-
1
tz.transition 1939, 10, :o4, 174927209, 72
-
1
tz.transition 1940, 5, :o5, 174943115, 72
-
1
tz.transition 1942, 11, :o6, 58335973, 24
-
1
tz.transition 1943, 3, :o5, 58339501, 24
-
1
tz.transition 1943, 10, :o6, 58344037, 24
-
1
tz.transition 1944, 4, :o5, 58348405, 24
-
1
tz.transition 1944, 10, :o6, 58352773, 24
-
1
tz.transition 1945, 4, :o5, 58357141, 24
-
1
tz.transition 1945, 9, :o6, 58361149, 24
-
1
tz.transition 1977, 4, :o5, 228877200
-
1
tz.transition 1977, 9, :o6, 243997200
-
1
tz.transition 1978, 4, :o5, 260326800
-
1
tz.transition 1978, 10, :o6, 276051600
-
1
tz.transition 1979, 4, :o5, 291776400
-
1
tz.transition 1979, 9, :o6, 307501200
-
1
tz.transition 1980, 4, :o5, 323830800
-
1
tz.transition 1980, 9, :o6, 338950800
-
1
tz.transition 1981, 3, :o5, 354675600
-
1
tz.transition 1981, 9, :o6, 370400400
-
1
tz.transition 1982, 3, :o5, 386125200
-
1
tz.transition 1982, 9, :o6, 401850000
-
1
tz.transition 1983, 3, :o5, 417574800
-
1
tz.transition 1983, 9, :o6, 433299600
-
1
tz.transition 1984, 3, :o5, 449024400
-
1
tz.transition 1984, 9, :o6, 465354000
-
1
tz.transition 1985, 3, :o5, 481078800
-
1
tz.transition 1985, 9, :o6, 496803600
-
1
tz.transition 1986, 3, :o5, 512528400
-
1
tz.transition 1986, 9, :o6, 528253200
-
1
tz.transition 1987, 3, :o5, 543978000
-
1
tz.transition 1987, 9, :o6, 559702800
-
1
tz.transition 1988, 3, :o5, 575427600
-
1
tz.transition 1988, 9, :o6, 591152400
-
1
tz.transition 1989, 3, :o5, 606877200
-
1
tz.transition 1989, 9, :o6, 622602000
-
1
tz.transition 1990, 3, :o5, 638326800
-
1
tz.transition 1990, 9, :o6, 654656400
-
1
tz.transition 1991, 3, :o5, 670381200
-
1
tz.transition 1991, 9, :o6, 686106000
-
1
tz.transition 1992, 3, :o5, 701830800
-
1
tz.transition 1992, 9, :o6, 717555600
-
1
tz.transition 1993, 3, :o5, 733280400
-
1
tz.transition 1993, 9, :o6, 749005200
-
1
tz.transition 1994, 3, :o5, 764730000
-
1
tz.transition 1994, 9, :o6, 780454800
-
1
tz.transition 1995, 3, :o5, 796179600
-
1
tz.transition 1995, 9, :o6, 811904400
-
1
tz.transition 1996, 3, :o5, 828234000
-
1
tz.transition 1996, 10, :o6, 846378000
-
1
tz.transition 1997, 3, :o5, 859683600
-
1
tz.transition 1997, 10, :o6, 877827600
-
1
tz.transition 1998, 3, :o5, 891133200
-
1
tz.transition 1998, 10, :o6, 909277200
-
1
tz.transition 1999, 3, :o5, 922582800
-
1
tz.transition 1999, 10, :o6, 941331600
-
1
tz.transition 2000, 3, :o5, 954032400
-
1
tz.transition 2000, 10, :o6, 972781200
-
1
tz.transition 2001, 3, :o5, 985482000
-
1
tz.transition 2001, 10, :o6, 1004230800
-
1
tz.transition 2002, 3, :o5, 1017536400
-
1
tz.transition 2002, 10, :o6, 1035680400
-
1
tz.transition 2003, 3, :o5, 1048986000
-
1
tz.transition 2003, 10, :o6, 1067130000
-
1
tz.transition 2004, 3, :o5, 1080435600
-
1
tz.transition 2004, 10, :o6, 1099184400
-
1
tz.transition 2005, 3, :o5, 1111885200
-
1
tz.transition 2005, 10, :o6, 1130634000
-
1
tz.transition 2006, 3, :o5, 1143334800
-
1
tz.transition 2006, 10, :o6, 1162083600
-
1
tz.transition 2007, 3, :o5, 1174784400
-
1
tz.transition 2007, 10, :o6, 1193533200
-
1
tz.transition 2008, 3, :o5, 1206838800
-
1
tz.transition 2008, 10, :o6, 1224982800
-
1
tz.transition 2009, 3, :o5, 1238288400
-
1
tz.transition 2009, 10, :o6, 1256432400
-
1
tz.transition 2010, 3, :o5, 1269738000
-
1
tz.transition 2010, 10, :o6, 1288486800
-
1
tz.transition 2011, 3, :o5, 1301187600
-
1
tz.transition 2011, 10, :o6, 1319936400
-
1
tz.transition 2012, 3, :o5, 1332637200
-
1
tz.transition 2012, 10, :o6, 1351386000
-
1
tz.transition 2013, 3, :o5, 1364691600
-
1
tz.transition 2013, 10, :o6, 1382835600
-
1
tz.transition 2014, 3, :o5, 1396141200
-
1
tz.transition 2014, 10, :o6, 1414285200
-
1
tz.transition 2015, 3, :o5, 1427590800
-
1
tz.transition 2015, 10, :o6, 1445734800
-
1
tz.transition 2016, 3, :o5, 1459040400
-
1
tz.transition 2016, 10, :o6, 1477789200
-
1
tz.transition 2017, 3, :o5, 1490490000
-
1
tz.transition 2017, 10, :o6, 1509238800
-
1
tz.transition 2018, 3, :o5, 1521939600
-
1
tz.transition 2018, 10, :o6, 1540688400
-
1
tz.transition 2019, 3, :o5, 1553994000
-
1
tz.transition 2019, 10, :o6, 1572138000
-
1
tz.transition 2020, 3, :o5, 1585443600
-
1
tz.transition 2020, 10, :o6, 1603587600
-
1
tz.transition 2021, 3, :o5, 1616893200
-
1
tz.transition 2021, 10, :o6, 1635642000
-
1
tz.transition 2022, 3, :o5, 1648342800
-
1
tz.transition 2022, 10, :o6, 1667091600
-
1
tz.transition 2023, 3, :o5, 1679792400
-
1
tz.transition 2023, 10, :o6, 1698541200
-
1
tz.transition 2024, 3, :o5, 1711846800
-
1
tz.transition 2024, 10, :o6, 1729990800
-
1
tz.transition 2025, 3, :o5, 1743296400
-
1
tz.transition 2025, 10, :o6, 1761440400
-
1
tz.transition 2026, 3, :o5, 1774746000
-
1
tz.transition 2026, 10, :o6, 1792890000
-
1
tz.transition 2027, 3, :o5, 1806195600
-
1
tz.transition 2027, 10, :o6, 1824944400
-
1
tz.transition 2028, 3, :o5, 1837645200
-
1
tz.transition 2028, 10, :o6, 1856394000
-
1
tz.transition 2029, 3, :o5, 1869094800
-
1
tz.transition 2029, 10, :o6, 1887843600
-
1
tz.transition 2030, 3, :o5, 1901149200
-
1
tz.transition 2030, 10, :o6, 1919293200
-
1
tz.transition 2031, 3, :o5, 1932598800
-
1
tz.transition 2031, 10, :o6, 1950742800
-
1
tz.transition 2032, 3, :o5, 1964048400
-
1
tz.transition 2032, 10, :o6, 1982797200
-
1
tz.transition 2033, 3, :o5, 1995498000
-
1
tz.transition 2033, 10, :o6, 2014246800
-
1
tz.transition 2034, 3, :o5, 2026947600
-
1
tz.transition 2034, 10, :o6, 2045696400
-
1
tz.transition 2035, 3, :o5, 2058397200
-
1
tz.transition 2035, 10, :o6, 2077146000
-
1
tz.transition 2036, 3, :o5, 2090451600
-
1
tz.transition 2036, 10, :o6, 2108595600
-
1
tz.transition 2037, 3, :o5, 2121901200
-
1
tz.transition 2037, 10, :o6, 2140045200
-
1
tz.transition 2038, 3, :o5, 59172253, 24
-
1
tz.transition 2038, 10, :o6, 59177461, 24
-
1
tz.transition 2039, 3, :o5, 59180989, 24
-
1
tz.transition 2039, 10, :o6, 59186197, 24
-
1
tz.transition 2040, 3, :o5, 59189725, 24
-
1
tz.transition 2040, 10, :o6, 59194933, 24
-
1
tz.transition 2041, 3, :o5, 59198629, 24
-
1
tz.transition 2041, 10, :o6, 59203669, 24
-
1
tz.transition 2042, 3, :o5, 59207365, 24
-
1
tz.transition 2042, 10, :o6, 59212405, 24
-
1
tz.transition 2043, 3, :o5, 59216101, 24
-
1
tz.transition 2043, 10, :o6, 59221141, 24
-
1
tz.transition 2044, 3, :o5, 59224837, 24
-
1
tz.transition 2044, 10, :o6, 59230045, 24
-
1
tz.transition 2045, 3, :o5, 59233573, 24
-
1
tz.transition 2045, 10, :o6, 59238781, 24
-
1
tz.transition 2046, 3, :o5, 59242309, 24
-
1
tz.transition 2046, 10, :o6, 59247517, 24
-
1
tz.transition 2047, 3, :o5, 59251213, 24
-
1
tz.transition 2047, 10, :o6, 59256253, 24
-
1
tz.transition 2048, 3, :o5, 59259949, 24
-
1
tz.transition 2048, 10, :o6, 59264989, 24
-
1
tz.transition 2049, 3, :o5, 59268685, 24
-
1
tz.transition 2049, 10, :o6, 59273893, 24
-
1
tz.transition 2050, 3, :o5, 59277421, 24
-
1
tz.transition 2050, 10, :o6, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Athens
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Athens' do |tz|
-
1
tz.offset :o0, 5692, 0, :LMT
-
1
tz.offset :o1, 5692, 0, :AMT
-
1
tz.offset :o2, 7200, 0, :EET
-
1
tz.offset :o3, 7200, 3600, :EEST
-
1
tz.offset :o4, 3600, 3600, :CEST
-
1
tz.offset :o5, 3600, 0, :CET
-
-
1
tz.transition 1895, 9, :o1, 52130529377, 21600
-
1
tz.transition 1916, 7, :o2, 3268447787, 1350
-
1
tz.transition 1932, 7, :o3, 29122745, 12
-
1
tz.transition 1932, 8, :o2, 19415611, 8
-
1
tz.transition 1941, 4, :o3, 29161097, 12
-
1
tz.transition 1941, 4, :o4, 19440915, 8
-
1
tz.transition 1942, 11, :o5, 58335973, 24
-
1
tz.transition 1943, 3, :o4, 58339523, 24
-
1
tz.transition 1943, 10, :o5, 29172017, 12
-
1
tz.transition 1944, 4, :o2, 58348427, 24
-
1
tz.transition 1952, 6, :o3, 29210333, 12
-
1
tz.transition 1952, 11, :o2, 19474547, 8
-
1
tz.transition 1975, 4, :o3, 166485600
-
1
tz.transition 1975, 11, :o2, 186184800
-
1
tz.transition 1976, 4, :o3, 198028800
-
1
tz.transition 1976, 10, :o2, 213753600
-
1
tz.transition 1977, 4, :o3, 228873600
-
1
tz.transition 1977, 9, :o2, 244080000
-
1
tz.transition 1978, 4, :o3, 260323200
-
1
tz.transition 1978, 9, :o2, 275446800
-
1
tz.transition 1979, 4, :o3, 291798000
-
1
tz.transition 1979, 9, :o2, 307407600
-
1
tz.transition 1980, 3, :o3, 323388000
-
1
tz.transition 1980, 9, :o2, 338936400
-
1
tz.transition 1981, 3, :o3, 354675600
-
1
tz.transition 1981, 9, :o2, 370400400
-
1
tz.transition 1982, 3, :o3, 386125200
-
1
tz.transition 1982, 9, :o2, 401850000
-
1
tz.transition 1983, 3, :o3, 417574800
-
1
tz.transition 1983, 9, :o2, 433299600
-
1
tz.transition 1984, 3, :o3, 449024400
-
1
tz.transition 1984, 9, :o2, 465354000
-
1
tz.transition 1985, 3, :o3, 481078800
-
1
tz.transition 1985, 9, :o2, 496803600
-
1
tz.transition 1986, 3, :o3, 512528400
-
1
tz.transition 1986, 9, :o2, 528253200
-
1
tz.transition 1987, 3, :o3, 543978000
-
1
tz.transition 1987, 9, :o2, 559702800
-
1
tz.transition 1988, 3, :o3, 575427600
-
1
tz.transition 1988, 9, :o2, 591152400
-
1
tz.transition 1989, 3, :o3, 606877200
-
1
tz.transition 1989, 9, :o2, 622602000
-
1
tz.transition 1990, 3, :o3, 638326800
-
1
tz.transition 1990, 9, :o2, 654656400
-
1
tz.transition 1991, 3, :o3, 670381200
-
1
tz.transition 1991, 9, :o2, 686106000
-
1
tz.transition 1992, 3, :o3, 701830800
-
1
tz.transition 1992, 9, :o2, 717555600
-
1
tz.transition 1993, 3, :o3, 733280400
-
1
tz.transition 1993, 9, :o2, 749005200
-
1
tz.transition 1994, 3, :o3, 764730000
-
1
tz.transition 1994, 9, :o2, 780454800
-
1
tz.transition 1995, 3, :o3, 796179600
-
1
tz.transition 1995, 9, :o2, 811904400
-
1
tz.transition 1996, 3, :o3, 828234000
-
1
tz.transition 1996, 10, :o2, 846378000
-
1
tz.transition 1997, 3, :o3, 859683600
-
1
tz.transition 1997, 10, :o2, 877827600
-
1
tz.transition 1998, 3, :o3, 891133200
-
1
tz.transition 1998, 10, :o2, 909277200
-
1
tz.transition 1999, 3, :o3, 922582800
-
1
tz.transition 1999, 10, :o2, 941331600
-
1
tz.transition 2000, 3, :o3, 954032400
-
1
tz.transition 2000, 10, :o2, 972781200
-
1
tz.transition 2001, 3, :o3, 985482000
-
1
tz.transition 2001, 10, :o2, 1004230800
-
1
tz.transition 2002, 3, :o3, 1017536400
-
1
tz.transition 2002, 10, :o2, 1035680400
-
1
tz.transition 2003, 3, :o3, 1048986000
-
1
tz.transition 2003, 10, :o2, 1067130000
-
1
tz.transition 2004, 3, :o3, 1080435600
-
1
tz.transition 2004, 10, :o2, 1099184400
-
1
tz.transition 2005, 3, :o3, 1111885200
-
1
tz.transition 2005, 10, :o2, 1130634000
-
1
tz.transition 2006, 3, :o3, 1143334800
-
1
tz.transition 2006, 10, :o2, 1162083600
-
1
tz.transition 2007, 3, :o3, 1174784400
-
1
tz.transition 2007, 10, :o2, 1193533200
-
1
tz.transition 2008, 3, :o3, 1206838800
-
1
tz.transition 2008, 10, :o2, 1224982800
-
1
tz.transition 2009, 3, :o3, 1238288400
-
1
tz.transition 2009, 10, :o2, 1256432400
-
1
tz.transition 2010, 3, :o3, 1269738000
-
1
tz.transition 2010, 10, :o2, 1288486800
-
1
tz.transition 2011, 3, :o3, 1301187600
-
1
tz.transition 2011, 10, :o2, 1319936400
-
1
tz.transition 2012, 3, :o3, 1332637200
-
1
tz.transition 2012, 10, :o2, 1351386000
-
1
tz.transition 2013, 3, :o3, 1364691600
-
1
tz.transition 2013, 10, :o2, 1382835600
-
1
tz.transition 2014, 3, :o3, 1396141200
-
1
tz.transition 2014, 10, :o2, 1414285200
-
1
tz.transition 2015, 3, :o3, 1427590800
-
1
tz.transition 2015, 10, :o2, 1445734800
-
1
tz.transition 2016, 3, :o3, 1459040400
-
1
tz.transition 2016, 10, :o2, 1477789200
-
1
tz.transition 2017, 3, :o3, 1490490000
-
1
tz.transition 2017, 10, :o2, 1509238800
-
1
tz.transition 2018, 3, :o3, 1521939600
-
1
tz.transition 2018, 10, :o2, 1540688400
-
1
tz.transition 2019, 3, :o3, 1553994000
-
1
tz.transition 2019, 10, :o2, 1572138000
-
1
tz.transition 2020, 3, :o3, 1585443600
-
1
tz.transition 2020, 10, :o2, 1603587600
-
1
tz.transition 2021, 3, :o3, 1616893200
-
1
tz.transition 2021, 10, :o2, 1635642000
-
1
tz.transition 2022, 3, :o3, 1648342800
-
1
tz.transition 2022, 10, :o2, 1667091600
-
1
tz.transition 2023, 3, :o3, 1679792400
-
1
tz.transition 2023, 10, :o2, 1698541200
-
1
tz.transition 2024, 3, :o3, 1711846800
-
1
tz.transition 2024, 10, :o2, 1729990800
-
1
tz.transition 2025, 3, :o3, 1743296400
-
1
tz.transition 2025, 10, :o2, 1761440400
-
1
tz.transition 2026, 3, :o3, 1774746000
-
1
tz.transition 2026, 10, :o2, 1792890000
-
1
tz.transition 2027, 3, :o3, 1806195600
-
1
tz.transition 2027, 10, :o2, 1824944400
-
1
tz.transition 2028, 3, :o3, 1837645200
-
1
tz.transition 2028, 10, :o2, 1856394000
-
1
tz.transition 2029, 3, :o3, 1869094800
-
1
tz.transition 2029, 10, :o2, 1887843600
-
1
tz.transition 2030, 3, :o3, 1901149200
-
1
tz.transition 2030, 10, :o2, 1919293200
-
1
tz.transition 2031, 3, :o3, 1932598800
-
1
tz.transition 2031, 10, :o2, 1950742800
-
1
tz.transition 2032, 3, :o3, 1964048400
-
1
tz.transition 2032, 10, :o2, 1982797200
-
1
tz.transition 2033, 3, :o3, 1995498000
-
1
tz.transition 2033, 10, :o2, 2014246800
-
1
tz.transition 2034, 3, :o3, 2026947600
-
1
tz.transition 2034, 10, :o2, 2045696400
-
1
tz.transition 2035, 3, :o3, 2058397200
-
1
tz.transition 2035, 10, :o2, 2077146000
-
1
tz.transition 2036, 3, :o3, 2090451600
-
1
tz.transition 2036, 10, :o2, 2108595600
-
1
tz.transition 2037, 3, :o3, 2121901200
-
1
tz.transition 2037, 10, :o2, 2140045200
-
1
tz.transition 2038, 3, :o3, 59172253, 24
-
1
tz.transition 2038, 10, :o2, 59177461, 24
-
1
tz.transition 2039, 3, :o3, 59180989, 24
-
1
tz.transition 2039, 10, :o2, 59186197, 24
-
1
tz.transition 2040, 3, :o3, 59189725, 24
-
1
tz.transition 2040, 10, :o2, 59194933, 24
-
1
tz.transition 2041, 3, :o3, 59198629, 24
-
1
tz.transition 2041, 10, :o2, 59203669, 24
-
1
tz.transition 2042, 3, :o3, 59207365, 24
-
1
tz.transition 2042, 10, :o2, 59212405, 24
-
1
tz.transition 2043, 3, :o3, 59216101, 24
-
1
tz.transition 2043, 10, :o2, 59221141, 24
-
1
tz.transition 2044, 3, :o3, 59224837, 24
-
1
tz.transition 2044, 10, :o2, 59230045, 24
-
1
tz.transition 2045, 3, :o3, 59233573, 24
-
1
tz.transition 2045, 10, :o2, 59238781, 24
-
1
tz.transition 2046, 3, :o3, 59242309, 24
-
1
tz.transition 2046, 10, :o2, 59247517, 24
-
1
tz.transition 2047, 3, :o3, 59251213, 24
-
1
tz.transition 2047, 10, :o2, 59256253, 24
-
1
tz.transition 2048, 3, :o3, 59259949, 24
-
1
tz.transition 2048, 10, :o2, 59264989, 24
-
1
tz.transition 2049, 3, :o3, 59268685, 24
-
1
tz.transition 2049, 10, :o2, 59273893, 24
-
1
tz.transition 2050, 3, :o3, 59277421, 24
-
1
tz.transition 2050, 10, :o2, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Belgrade
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Belgrade' do |tz|
-
1
tz.offset :o0, 4920, 0, :LMT
-
1
tz.offset :o1, 3600, 0, :CET
-
1
tz.offset :o2, 3600, 3600, :CEST
-
-
1
tz.transition 1883, 12, :o1, 1734607039, 720
-
1
tz.transition 1941, 4, :o2, 29161241, 12
-
1
tz.transition 1942, 11, :o1, 58335973, 24
-
1
tz.transition 1943, 3, :o2, 58339501, 24
-
1
tz.transition 1943, 10, :o1, 58344037, 24
-
1
tz.transition 1944, 4, :o2, 58348405, 24
-
1
tz.transition 1944, 10, :o1, 58352773, 24
-
1
tz.transition 1945, 5, :o2, 58358005, 24
-
1
tz.transition 1945, 9, :o1, 58361149, 24
-
1
tz.transition 1983, 3, :o2, 417574800
-
1
tz.transition 1983, 9, :o1, 433299600
-
1
tz.transition 1984, 3, :o2, 449024400
-
1
tz.transition 1984, 9, :o1, 465354000
-
1
tz.transition 1985, 3, :o2, 481078800
-
1
tz.transition 1985, 9, :o1, 496803600
-
1
tz.transition 1986, 3, :o2, 512528400
-
1
tz.transition 1986, 9, :o1, 528253200
-
1
tz.transition 1987, 3, :o2, 543978000
-
1
tz.transition 1987, 9, :o1, 559702800
-
1
tz.transition 1988, 3, :o2, 575427600
-
1
tz.transition 1988, 9, :o1, 591152400
-
1
tz.transition 1989, 3, :o2, 606877200
-
1
tz.transition 1989, 9, :o1, 622602000
-
1
tz.transition 1990, 3, :o2, 638326800
-
1
tz.transition 1990, 9, :o1, 654656400
-
1
tz.transition 1991, 3, :o2, 670381200
-
1
tz.transition 1991, 9, :o1, 686106000
-
1
tz.transition 1992, 3, :o2, 701830800
-
1
tz.transition 1992, 9, :o1, 717555600
-
1
tz.transition 1993, 3, :o2, 733280400
-
1
tz.transition 1993, 9, :o1, 749005200
-
1
tz.transition 1994, 3, :o2, 764730000
-
1
tz.transition 1994, 9, :o1, 780454800
-
1
tz.transition 1995, 3, :o2, 796179600
-
1
tz.transition 1995, 9, :o1, 811904400
-
1
tz.transition 1996, 3, :o2, 828234000
-
1
tz.transition 1996, 10, :o1, 846378000
-
1
tz.transition 1997, 3, :o2, 859683600
-
1
tz.transition 1997, 10, :o1, 877827600
-
1
tz.transition 1998, 3, :o2, 891133200
-
1
tz.transition 1998, 10, :o1, 909277200
-
1
tz.transition 1999, 3, :o2, 922582800
-
1
tz.transition 1999, 10, :o1, 941331600
-
1
tz.transition 2000, 3, :o2, 954032400
-
1
tz.transition 2000, 10, :o1, 972781200
-
1
tz.transition 2001, 3, :o2, 985482000
-
1
tz.transition 2001, 10, :o1, 1004230800
-
1
tz.transition 2002, 3, :o2, 1017536400
-
1
tz.transition 2002, 10, :o1, 1035680400
-
1
tz.transition 2003, 3, :o2, 1048986000
-
1
tz.transition 2003, 10, :o1, 1067130000
-
1
tz.transition 2004, 3, :o2, 1080435600
-
1
tz.transition 2004, 10, :o1, 1099184400
-
1
tz.transition 2005, 3, :o2, 1111885200
-
1
tz.transition 2005, 10, :o1, 1130634000
-
1
tz.transition 2006, 3, :o2, 1143334800
-
1
tz.transition 2006, 10, :o1, 1162083600
-
1
tz.transition 2007, 3, :o2, 1174784400
-
1
tz.transition 2007, 10, :o1, 1193533200
-
1
tz.transition 2008, 3, :o2, 1206838800
-
1
tz.transition 2008, 10, :o1, 1224982800
-
1
tz.transition 2009, 3, :o2, 1238288400
-
1
tz.transition 2009, 10, :o1, 1256432400
-
1
tz.transition 2010, 3, :o2, 1269738000
-
1
tz.transition 2010, 10, :o1, 1288486800
-
1
tz.transition 2011, 3, :o2, 1301187600
-
1
tz.transition 2011, 10, :o1, 1319936400
-
1
tz.transition 2012, 3, :o2, 1332637200
-
1
tz.transition 2012, 10, :o1, 1351386000
-
1
tz.transition 2013, 3, :o2, 1364691600
-
1
tz.transition 2013, 10, :o1, 1382835600
-
1
tz.transition 2014, 3, :o2, 1396141200
-
1
tz.transition 2014, 10, :o1, 1414285200
-
1
tz.transition 2015, 3, :o2, 1427590800
-
1
tz.transition 2015, 10, :o1, 1445734800
-
1
tz.transition 2016, 3, :o2, 1459040400
-
1
tz.transition 2016, 10, :o1, 1477789200
-
1
tz.transition 2017, 3, :o2, 1490490000
-
1
tz.transition 2017, 10, :o1, 1509238800
-
1
tz.transition 2018, 3, :o2, 1521939600
-
1
tz.transition 2018, 10, :o1, 1540688400
-
1
tz.transition 2019, 3, :o2, 1553994000
-
1
tz.transition 2019, 10, :o1, 1572138000
-
1
tz.transition 2020, 3, :o2, 1585443600
-
1
tz.transition 2020, 10, :o1, 1603587600
-
1
tz.transition 2021, 3, :o2, 1616893200
-
1
tz.transition 2021, 10, :o1, 1635642000
-
1
tz.transition 2022, 3, :o2, 1648342800
-
1
tz.transition 2022, 10, :o1, 1667091600
-
1
tz.transition 2023, 3, :o2, 1679792400
-
1
tz.transition 2023, 10, :o1, 1698541200
-
1
tz.transition 2024, 3, :o2, 1711846800
-
1
tz.transition 2024, 10, :o1, 1729990800
-
1
tz.transition 2025, 3, :o2, 1743296400
-
1
tz.transition 2025, 10, :o1, 1761440400
-
1
tz.transition 2026, 3, :o2, 1774746000
-
1
tz.transition 2026, 10, :o1, 1792890000
-
1
tz.transition 2027, 3, :o2, 1806195600
-
1
tz.transition 2027, 10, :o1, 1824944400
-
1
tz.transition 2028, 3, :o2, 1837645200
-
1
tz.transition 2028, 10, :o1, 1856394000
-
1
tz.transition 2029, 3, :o2, 1869094800
-
1
tz.transition 2029, 10, :o1, 1887843600
-
1
tz.transition 2030, 3, :o2, 1901149200
-
1
tz.transition 2030, 10, :o1, 1919293200
-
1
tz.transition 2031, 3, :o2, 1932598800
-
1
tz.transition 2031, 10, :o1, 1950742800
-
1
tz.transition 2032, 3, :o2, 1964048400
-
1
tz.transition 2032, 10, :o1, 1982797200
-
1
tz.transition 2033, 3, :o2, 1995498000
-
1
tz.transition 2033, 10, :o1, 2014246800
-
1
tz.transition 2034, 3, :o2, 2026947600
-
1
tz.transition 2034, 10, :o1, 2045696400
-
1
tz.transition 2035, 3, :o2, 2058397200
-
1
tz.transition 2035, 10, :o1, 2077146000
-
1
tz.transition 2036, 3, :o2, 2090451600
-
1
tz.transition 2036, 10, :o1, 2108595600
-
1
tz.transition 2037, 3, :o2, 2121901200
-
1
tz.transition 2037, 10, :o1, 2140045200
-
1
tz.transition 2038, 3, :o2, 59172253, 24
-
1
tz.transition 2038, 10, :o1, 59177461, 24
-
1
tz.transition 2039, 3, :o2, 59180989, 24
-
1
tz.transition 2039, 10, :o1, 59186197, 24
-
1
tz.transition 2040, 3, :o2, 59189725, 24
-
1
tz.transition 2040, 10, :o1, 59194933, 24
-
1
tz.transition 2041, 3, :o2, 59198629, 24
-
1
tz.transition 2041, 10, :o1, 59203669, 24
-
1
tz.transition 2042, 3, :o2, 59207365, 24
-
1
tz.transition 2042, 10, :o1, 59212405, 24
-
1
tz.transition 2043, 3, :o2, 59216101, 24
-
1
tz.transition 2043, 10, :o1, 59221141, 24
-
1
tz.transition 2044, 3, :o2, 59224837, 24
-
1
tz.transition 2044, 10, :o1, 59230045, 24
-
1
tz.transition 2045, 3, :o2, 59233573, 24
-
1
tz.transition 2045, 10, :o1, 59238781, 24
-
1
tz.transition 2046, 3, :o2, 59242309, 24
-
1
tz.transition 2046, 10, :o1, 59247517, 24
-
1
tz.transition 2047, 3, :o2, 59251213, 24
-
1
tz.transition 2047, 10, :o1, 59256253, 24
-
1
tz.transition 2048, 3, :o2, 59259949, 24
-
1
tz.transition 2048, 10, :o1, 59264989, 24
-
1
tz.transition 2049, 3, :o2, 59268685, 24
-
1
tz.transition 2049, 10, :o1, 59273893, 24
-
1
tz.transition 2050, 3, :o2, 59277421, 24
-
1
tz.transition 2050, 10, :o1, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Berlin
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Berlin' do |tz|
-
1
tz.offset :o0, 3208, 0, :LMT
-
1
tz.offset :o1, 3600, 0, :CET
-
1
tz.offset :o2, 3600, 3600, :CEST
-
1
tz.offset :o3, 3600, 7200, :CEMT
-
-
1
tz.transition 1893, 3, :o1, 26055588199, 10800
-
1
tz.transition 1916, 4, :o2, 29051813, 12
-
1
tz.transition 1916, 9, :o1, 58107299, 24
-
1
tz.transition 1917, 4, :o2, 58112029, 24
-
1
tz.transition 1917, 9, :o1, 58115725, 24
-
1
tz.transition 1918, 4, :o2, 58120765, 24
-
1
tz.transition 1918, 9, :o1, 58124461, 24
-
1
tz.transition 1940, 4, :o2, 58313293, 24
-
1
tz.transition 1942, 11, :o1, 58335973, 24
-
1
tz.transition 1943, 3, :o2, 58339501, 24
-
1
tz.transition 1943, 10, :o1, 58344037, 24
-
1
tz.transition 1944, 4, :o2, 58348405, 24
-
1
tz.transition 1944, 10, :o1, 58352773, 24
-
1
tz.transition 1945, 4, :o2, 58357141, 24
-
1
tz.transition 1945, 5, :o3, 4863199, 2
-
1
tz.transition 1945, 9, :o2, 4863445, 2
-
1
tz.transition 1945, 11, :o1, 58362661, 24
-
1
tz.transition 1946, 4, :o2, 58366189, 24
-
1
tz.transition 1946, 10, :o1, 58370413, 24
-
1
tz.transition 1947, 4, :o2, 29187379, 12
-
1
tz.transition 1947, 5, :o3, 58375597, 24
-
1
tz.transition 1947, 6, :o2, 4864731, 2
-
1
tz.transition 1947, 10, :o1, 58379125, 24
-
1
tz.transition 1948, 4, :o2, 58383829, 24
-
1
tz.transition 1948, 10, :o1, 58387861, 24
-
1
tz.transition 1949, 4, :o2, 58392397, 24
-
1
tz.transition 1949, 10, :o1, 58396597, 24
-
1
tz.transition 1980, 4, :o2, 323830800
-
1
tz.transition 1980, 9, :o1, 338950800
-
1
tz.transition 1981, 3, :o2, 354675600
-
1
tz.transition 1981, 9, :o1, 370400400
-
1
tz.transition 1982, 3, :o2, 386125200
-
1
tz.transition 1982, 9, :o1, 401850000
-
1
tz.transition 1983, 3, :o2, 417574800
-
1
tz.transition 1983, 9, :o1, 433299600
-
1
tz.transition 1984, 3, :o2, 449024400
-
1
tz.transition 1984, 9, :o1, 465354000
-
1
tz.transition 1985, 3, :o2, 481078800
-
1
tz.transition 1985, 9, :o1, 496803600
-
1
tz.transition 1986, 3, :o2, 512528400
-
1
tz.transition 1986, 9, :o1, 528253200
-
1
tz.transition 1987, 3, :o2, 543978000
-
1
tz.transition 1987, 9, :o1, 559702800
-
1
tz.transition 1988, 3, :o2, 575427600
-
1
tz.transition 1988, 9, :o1, 591152400
-
1
tz.transition 1989, 3, :o2, 606877200
-
1
tz.transition 1989, 9, :o1, 622602000
-
1
tz.transition 1990, 3, :o2, 638326800
-
1
tz.transition 1990, 9, :o1, 654656400
-
1
tz.transition 1991, 3, :o2, 670381200
-
1
tz.transition 1991, 9, :o1, 686106000
-
1
tz.transition 1992, 3, :o2, 701830800
-
1
tz.transition 1992, 9, :o1, 717555600
-
1
tz.transition 1993, 3, :o2, 733280400
-
1
tz.transition 1993, 9, :o1, 749005200
-
1
tz.transition 1994, 3, :o2, 764730000
-
1
tz.transition 1994, 9, :o1, 780454800
-
1
tz.transition 1995, 3, :o2, 796179600
-
1
tz.transition 1995, 9, :o1, 811904400
-
1
tz.transition 1996, 3, :o2, 828234000
-
1
tz.transition 1996, 10, :o1, 846378000
-
1
tz.transition 1997, 3, :o2, 859683600
-
1
tz.transition 1997, 10, :o1, 877827600
-
1
tz.transition 1998, 3, :o2, 891133200
-
1
tz.transition 1998, 10, :o1, 909277200
-
1
tz.transition 1999, 3, :o2, 922582800
-
1
tz.transition 1999, 10, :o1, 941331600
-
1
tz.transition 2000, 3, :o2, 954032400
-
1
tz.transition 2000, 10, :o1, 972781200
-
1
tz.transition 2001, 3, :o2, 985482000
-
1
tz.transition 2001, 10, :o1, 1004230800
-
1
tz.transition 2002, 3, :o2, 1017536400
-
1
tz.transition 2002, 10, :o1, 1035680400
-
1
tz.transition 2003, 3, :o2, 1048986000
-
1
tz.transition 2003, 10, :o1, 1067130000
-
1
tz.transition 2004, 3, :o2, 1080435600
-
1
tz.transition 2004, 10, :o1, 1099184400
-
1
tz.transition 2005, 3, :o2, 1111885200
-
1
tz.transition 2005, 10, :o1, 1130634000
-
1
tz.transition 2006, 3, :o2, 1143334800
-
1
tz.transition 2006, 10, :o1, 1162083600
-
1
tz.transition 2007, 3, :o2, 1174784400
-
1
tz.transition 2007, 10, :o1, 1193533200
-
1
tz.transition 2008, 3, :o2, 1206838800
-
1
tz.transition 2008, 10, :o1, 1224982800
-
1
tz.transition 2009, 3, :o2, 1238288400
-
1
tz.transition 2009, 10, :o1, 1256432400
-
1
tz.transition 2010, 3, :o2, 1269738000
-
1
tz.transition 2010, 10, :o1, 1288486800
-
1
tz.transition 2011, 3, :o2, 1301187600
-
1
tz.transition 2011, 10, :o1, 1319936400
-
1
tz.transition 2012, 3, :o2, 1332637200
-
1
tz.transition 2012, 10, :o1, 1351386000
-
1
tz.transition 2013, 3, :o2, 1364691600
-
1
tz.transition 2013, 10, :o1, 1382835600
-
1
tz.transition 2014, 3, :o2, 1396141200
-
1
tz.transition 2014, 10, :o1, 1414285200
-
1
tz.transition 2015, 3, :o2, 1427590800
-
1
tz.transition 2015, 10, :o1, 1445734800
-
1
tz.transition 2016, 3, :o2, 1459040400
-
1
tz.transition 2016, 10, :o1, 1477789200
-
1
tz.transition 2017, 3, :o2, 1490490000
-
1
tz.transition 2017, 10, :o1, 1509238800
-
1
tz.transition 2018, 3, :o2, 1521939600
-
1
tz.transition 2018, 10, :o1, 1540688400
-
1
tz.transition 2019, 3, :o2, 1553994000
-
1
tz.transition 2019, 10, :o1, 1572138000
-
1
tz.transition 2020, 3, :o2, 1585443600
-
1
tz.transition 2020, 10, :o1, 1603587600
-
1
tz.transition 2021, 3, :o2, 1616893200
-
1
tz.transition 2021, 10, :o1, 1635642000
-
1
tz.transition 2022, 3, :o2, 1648342800
-
1
tz.transition 2022, 10, :o1, 1667091600
-
1
tz.transition 2023, 3, :o2, 1679792400
-
1
tz.transition 2023, 10, :o1, 1698541200
-
1
tz.transition 2024, 3, :o2, 1711846800
-
1
tz.transition 2024, 10, :o1, 1729990800
-
1
tz.transition 2025, 3, :o2, 1743296400
-
1
tz.transition 2025, 10, :o1, 1761440400
-
1
tz.transition 2026, 3, :o2, 1774746000
-
1
tz.transition 2026, 10, :o1, 1792890000
-
1
tz.transition 2027, 3, :o2, 1806195600
-
1
tz.transition 2027, 10, :o1, 1824944400
-
1
tz.transition 2028, 3, :o2, 1837645200
-
1
tz.transition 2028, 10, :o1, 1856394000
-
1
tz.transition 2029, 3, :o2, 1869094800
-
1
tz.transition 2029, 10, :o1, 1887843600
-
1
tz.transition 2030, 3, :o2, 1901149200
-
1
tz.transition 2030, 10, :o1, 1919293200
-
1
tz.transition 2031, 3, :o2, 1932598800
-
1
tz.transition 2031, 10, :o1, 1950742800
-
1
tz.transition 2032, 3, :o2, 1964048400
-
1
tz.transition 2032, 10, :o1, 1982797200
-
1
tz.transition 2033, 3, :o2, 1995498000
-
1
tz.transition 2033, 10, :o1, 2014246800
-
1
tz.transition 2034, 3, :o2, 2026947600
-
1
tz.transition 2034, 10, :o1, 2045696400
-
1
tz.transition 2035, 3, :o2, 2058397200
-
1
tz.transition 2035, 10, :o1, 2077146000
-
1
tz.transition 2036, 3, :o2, 2090451600
-
1
tz.transition 2036, 10, :o1, 2108595600
-
1
tz.transition 2037, 3, :o2, 2121901200
-
1
tz.transition 2037, 10, :o1, 2140045200
-
1
tz.transition 2038, 3, :o2, 59172253, 24
-
1
tz.transition 2038, 10, :o1, 59177461, 24
-
1
tz.transition 2039, 3, :o2, 59180989, 24
-
1
tz.transition 2039, 10, :o1, 59186197, 24
-
1
tz.transition 2040, 3, :o2, 59189725, 24
-
1
tz.transition 2040, 10, :o1, 59194933, 24
-
1
tz.transition 2041, 3, :o2, 59198629, 24
-
1
tz.transition 2041, 10, :o1, 59203669, 24
-
1
tz.transition 2042, 3, :o2, 59207365, 24
-
1
tz.transition 2042, 10, :o1, 59212405, 24
-
1
tz.transition 2043, 3, :o2, 59216101, 24
-
1
tz.transition 2043, 10, :o1, 59221141, 24
-
1
tz.transition 2044, 3, :o2, 59224837, 24
-
1
tz.transition 2044, 10, :o1, 59230045, 24
-
1
tz.transition 2045, 3, :o2, 59233573, 24
-
1
tz.transition 2045, 10, :o1, 59238781, 24
-
1
tz.transition 2046, 3, :o2, 59242309, 24
-
1
tz.transition 2046, 10, :o1, 59247517, 24
-
1
tz.transition 2047, 3, :o2, 59251213, 24
-
1
tz.transition 2047, 10, :o1, 59256253, 24
-
1
tz.transition 2048, 3, :o2, 59259949, 24
-
1
tz.transition 2048, 10, :o1, 59264989, 24
-
1
tz.transition 2049, 3, :o2, 59268685, 24
-
1
tz.transition 2049, 10, :o1, 59273893, 24
-
1
tz.transition 2050, 3, :o2, 59277421, 24
-
1
tz.transition 2050, 10, :o1, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Bratislava
-
1
include TimezoneDefinition
-
-
1
linked_timezone 'Europe/Bratislava', 'Europe/Prague'
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Brussels
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Brussels' do |tz|
-
1
tz.offset :o0, 1050, 0, :LMT
-
1
tz.offset :o1, 1050, 0, :BMT
-
1
tz.offset :o2, 0, 0, :WET
-
1
tz.offset :o3, 3600, 0, :CET
-
1
tz.offset :o4, 3600, 3600, :CEST
-
1
tz.offset :o5, 0, 3600, :WEST
-
-
1
tz.transition 1879, 12, :o1, 1386844121, 576
-
1
tz.transition 1892, 5, :o2, 1389438713, 576
-
1
tz.transition 1914, 11, :o3, 4840889, 2
-
1
tz.transition 1916, 4, :o4, 58103627, 24
-
1
tz.transition 1916, 9, :o3, 58107299, 24
-
1
tz.transition 1917, 4, :o4, 58112029, 24
-
1
tz.transition 1917, 9, :o3, 58115725, 24
-
1
tz.transition 1918, 4, :o4, 58120765, 24
-
1
tz.transition 1918, 9, :o3, 58124461, 24
-
1
tz.transition 1918, 11, :o2, 58125815, 24
-
1
tz.transition 1919, 3, :o5, 58128467, 24
-
1
tz.transition 1919, 10, :o2, 58133675, 24
-
1
tz.transition 1920, 2, :o5, 58136867, 24
-
1
tz.transition 1920, 10, :o2, 58142915, 24
-
1
tz.transition 1921, 3, :o5, 58146323, 24
-
1
tz.transition 1921, 10, :o2, 58151723, 24
-
1
tz.transition 1922, 3, :o5, 58155347, 24
-
1
tz.transition 1922, 10, :o2, 58160051, 24
-
1
tz.transition 1923, 4, :o5, 58164755, 24
-
1
tz.transition 1923, 10, :o2, 58168787, 24
-
1
tz.transition 1924, 3, :o5, 58172987, 24
-
1
tz.transition 1924, 10, :o2, 58177523, 24
-
1
tz.transition 1925, 4, :o5, 58181891, 24
-
1
tz.transition 1925, 10, :o2, 58186259, 24
-
1
tz.transition 1926, 4, :o5, 58190963, 24
-
1
tz.transition 1926, 10, :o2, 58194995, 24
-
1
tz.transition 1927, 4, :o5, 58199531, 24
-
1
tz.transition 1927, 10, :o2, 58203731, 24
-
1
tz.transition 1928, 4, :o5, 58208435, 24
-
1
tz.transition 1928, 10, :o2, 29106319, 12
-
1
tz.transition 1929, 4, :o5, 29108671, 12
-
1
tz.transition 1929, 10, :o2, 29110687, 12
-
1
tz.transition 1930, 4, :o5, 29112955, 12
-
1
tz.transition 1930, 10, :o2, 29115055, 12
-
1
tz.transition 1931, 4, :o5, 29117407, 12
-
1
tz.transition 1931, 10, :o2, 29119423, 12
-
1
tz.transition 1932, 4, :o5, 29121607, 12
-
1
tz.transition 1932, 10, :o2, 29123791, 12
-
1
tz.transition 1933, 3, :o5, 29125891, 12
-
1
tz.transition 1933, 10, :o2, 29128243, 12
-
1
tz.transition 1934, 4, :o5, 29130427, 12
-
1
tz.transition 1934, 10, :o2, 29132611, 12
-
1
tz.transition 1935, 3, :o5, 29134711, 12
-
1
tz.transition 1935, 10, :o2, 29136979, 12
-
1
tz.transition 1936, 4, :o5, 29139331, 12
-
1
tz.transition 1936, 10, :o2, 29141347, 12
-
1
tz.transition 1937, 4, :o5, 29143531, 12
-
1
tz.transition 1937, 10, :o2, 29145715, 12
-
1
tz.transition 1938, 3, :o5, 29147815, 12
-
1
tz.transition 1938, 10, :o2, 29150083, 12
-
1
tz.transition 1939, 4, :o5, 29152435, 12
-
1
tz.transition 1939, 11, :o2, 29155039, 12
-
1
tz.transition 1940, 2, :o5, 29156215, 12
-
1
tz.transition 1940, 5, :o4, 29157235, 12
-
1
tz.transition 1942, 11, :o3, 58335973, 24
-
1
tz.transition 1943, 3, :o4, 58339501, 24
-
1
tz.transition 1943, 10, :o3, 58344037, 24
-
1
tz.transition 1944, 4, :o4, 58348405, 24
-
1
tz.transition 1944, 9, :o3, 58352413, 24
-
1
tz.transition 1945, 4, :o4, 58357141, 24
-
1
tz.transition 1945, 9, :o3, 58361149, 24
-
1
tz.transition 1946, 5, :o4, 58367029, 24
-
1
tz.transition 1946, 10, :o3, 58370413, 24
-
1
tz.transition 1977, 4, :o4, 228877200
-
1
tz.transition 1977, 9, :o3, 243997200
-
1
tz.transition 1978, 4, :o4, 260326800
-
1
tz.transition 1978, 10, :o3, 276051600
-
1
tz.transition 1979, 4, :o4, 291776400
-
1
tz.transition 1979, 9, :o3, 307501200
-
1
tz.transition 1980, 4, :o4, 323830800
-
1
tz.transition 1980, 9, :o3, 338950800
-
1
tz.transition 1981, 3, :o4, 354675600
-
1
tz.transition 1981, 9, :o3, 370400400
-
1
tz.transition 1982, 3, :o4, 386125200
-
1
tz.transition 1982, 9, :o3, 401850000
-
1
tz.transition 1983, 3, :o4, 417574800
-
1
tz.transition 1983, 9, :o3, 433299600
-
1
tz.transition 1984, 3, :o4, 449024400
-
1
tz.transition 1984, 9, :o3, 465354000
-
1
tz.transition 1985, 3, :o4, 481078800
-
1
tz.transition 1985, 9, :o3, 496803600
-
1
tz.transition 1986, 3, :o4, 512528400
-
1
tz.transition 1986, 9, :o3, 528253200
-
1
tz.transition 1987, 3, :o4, 543978000
-
1
tz.transition 1987, 9, :o3, 559702800
-
1
tz.transition 1988, 3, :o4, 575427600
-
1
tz.transition 1988, 9, :o3, 591152400
-
1
tz.transition 1989, 3, :o4, 606877200
-
1
tz.transition 1989, 9, :o3, 622602000
-
1
tz.transition 1990, 3, :o4, 638326800
-
1
tz.transition 1990, 9, :o3, 654656400
-
1
tz.transition 1991, 3, :o4, 670381200
-
1
tz.transition 1991, 9, :o3, 686106000
-
1
tz.transition 1992, 3, :o4, 701830800
-
1
tz.transition 1992, 9, :o3, 717555600
-
1
tz.transition 1993, 3, :o4, 733280400
-
1
tz.transition 1993, 9, :o3, 749005200
-
1
tz.transition 1994, 3, :o4, 764730000
-
1
tz.transition 1994, 9, :o3, 780454800
-
1
tz.transition 1995, 3, :o4, 796179600
-
1
tz.transition 1995, 9, :o3, 811904400
-
1
tz.transition 1996, 3, :o4, 828234000
-
1
tz.transition 1996, 10, :o3, 846378000
-
1
tz.transition 1997, 3, :o4, 859683600
-
1
tz.transition 1997, 10, :o3, 877827600
-
1
tz.transition 1998, 3, :o4, 891133200
-
1
tz.transition 1998, 10, :o3, 909277200
-
1
tz.transition 1999, 3, :o4, 922582800
-
1
tz.transition 1999, 10, :o3, 941331600
-
1
tz.transition 2000, 3, :o4, 954032400
-
1
tz.transition 2000, 10, :o3, 972781200
-
1
tz.transition 2001, 3, :o4, 985482000
-
1
tz.transition 2001, 10, :o3, 1004230800
-
1
tz.transition 2002, 3, :o4, 1017536400
-
1
tz.transition 2002, 10, :o3, 1035680400
-
1
tz.transition 2003, 3, :o4, 1048986000
-
1
tz.transition 2003, 10, :o3, 1067130000
-
1
tz.transition 2004, 3, :o4, 1080435600
-
1
tz.transition 2004, 10, :o3, 1099184400
-
1
tz.transition 2005, 3, :o4, 1111885200
-
1
tz.transition 2005, 10, :o3, 1130634000
-
1
tz.transition 2006, 3, :o4, 1143334800
-
1
tz.transition 2006, 10, :o3, 1162083600
-
1
tz.transition 2007, 3, :o4, 1174784400
-
1
tz.transition 2007, 10, :o3, 1193533200
-
1
tz.transition 2008, 3, :o4, 1206838800
-
1
tz.transition 2008, 10, :o3, 1224982800
-
1
tz.transition 2009, 3, :o4, 1238288400
-
1
tz.transition 2009, 10, :o3, 1256432400
-
1
tz.transition 2010, 3, :o4, 1269738000
-
1
tz.transition 2010, 10, :o3, 1288486800
-
1
tz.transition 2011, 3, :o4, 1301187600
-
1
tz.transition 2011, 10, :o3, 1319936400
-
1
tz.transition 2012, 3, :o4, 1332637200
-
1
tz.transition 2012, 10, :o3, 1351386000
-
1
tz.transition 2013, 3, :o4, 1364691600
-
1
tz.transition 2013, 10, :o3, 1382835600
-
1
tz.transition 2014, 3, :o4, 1396141200
-
1
tz.transition 2014, 10, :o3, 1414285200
-
1
tz.transition 2015, 3, :o4, 1427590800
-
1
tz.transition 2015, 10, :o3, 1445734800
-
1
tz.transition 2016, 3, :o4, 1459040400
-
1
tz.transition 2016, 10, :o3, 1477789200
-
1
tz.transition 2017, 3, :o4, 1490490000
-
1
tz.transition 2017, 10, :o3, 1509238800
-
1
tz.transition 2018, 3, :o4, 1521939600
-
1
tz.transition 2018, 10, :o3, 1540688400
-
1
tz.transition 2019, 3, :o4, 1553994000
-
1
tz.transition 2019, 10, :o3, 1572138000
-
1
tz.transition 2020, 3, :o4, 1585443600
-
1
tz.transition 2020, 10, :o3, 1603587600
-
1
tz.transition 2021, 3, :o4, 1616893200
-
1
tz.transition 2021, 10, :o3, 1635642000
-
1
tz.transition 2022, 3, :o4, 1648342800
-
1
tz.transition 2022, 10, :o3, 1667091600
-
1
tz.transition 2023, 3, :o4, 1679792400
-
1
tz.transition 2023, 10, :o3, 1698541200
-
1
tz.transition 2024, 3, :o4, 1711846800
-
1
tz.transition 2024, 10, :o3, 1729990800
-
1
tz.transition 2025, 3, :o4, 1743296400
-
1
tz.transition 2025, 10, :o3, 1761440400
-
1
tz.transition 2026, 3, :o4, 1774746000
-
1
tz.transition 2026, 10, :o3, 1792890000
-
1
tz.transition 2027, 3, :o4, 1806195600
-
1
tz.transition 2027, 10, :o3, 1824944400
-
1
tz.transition 2028, 3, :o4, 1837645200
-
1
tz.transition 2028, 10, :o3, 1856394000
-
1
tz.transition 2029, 3, :o4, 1869094800
-
1
tz.transition 2029, 10, :o3, 1887843600
-
1
tz.transition 2030, 3, :o4, 1901149200
-
1
tz.transition 2030, 10, :o3, 1919293200
-
1
tz.transition 2031, 3, :o4, 1932598800
-
1
tz.transition 2031, 10, :o3, 1950742800
-
1
tz.transition 2032, 3, :o4, 1964048400
-
1
tz.transition 2032, 10, :o3, 1982797200
-
1
tz.transition 2033, 3, :o4, 1995498000
-
1
tz.transition 2033, 10, :o3, 2014246800
-
1
tz.transition 2034, 3, :o4, 2026947600
-
1
tz.transition 2034, 10, :o3, 2045696400
-
1
tz.transition 2035, 3, :o4, 2058397200
-
1
tz.transition 2035, 10, :o3, 2077146000
-
1
tz.transition 2036, 3, :o4, 2090451600
-
1
tz.transition 2036, 10, :o3, 2108595600
-
1
tz.transition 2037, 3, :o4, 2121901200
-
1
tz.transition 2037, 10, :o3, 2140045200
-
1
tz.transition 2038, 3, :o4, 59172253, 24
-
1
tz.transition 2038, 10, :o3, 59177461, 24
-
1
tz.transition 2039, 3, :o4, 59180989, 24
-
1
tz.transition 2039, 10, :o3, 59186197, 24
-
1
tz.transition 2040, 3, :o4, 59189725, 24
-
1
tz.transition 2040, 10, :o3, 59194933, 24
-
1
tz.transition 2041, 3, :o4, 59198629, 24
-
1
tz.transition 2041, 10, :o3, 59203669, 24
-
1
tz.transition 2042, 3, :o4, 59207365, 24
-
1
tz.transition 2042, 10, :o3, 59212405, 24
-
1
tz.transition 2043, 3, :o4, 59216101, 24
-
1
tz.transition 2043, 10, :o3, 59221141, 24
-
1
tz.transition 2044, 3, :o4, 59224837, 24
-
1
tz.transition 2044, 10, :o3, 59230045, 24
-
1
tz.transition 2045, 3, :o4, 59233573, 24
-
1
tz.transition 2045, 10, :o3, 59238781, 24
-
1
tz.transition 2046, 3, :o4, 59242309, 24
-
1
tz.transition 2046, 10, :o3, 59247517, 24
-
1
tz.transition 2047, 3, :o4, 59251213, 24
-
1
tz.transition 2047, 10, :o3, 59256253, 24
-
1
tz.transition 2048, 3, :o4, 59259949, 24
-
1
tz.transition 2048, 10, :o3, 59264989, 24
-
1
tz.transition 2049, 3, :o4, 59268685, 24
-
1
tz.transition 2049, 10, :o3, 59273893, 24
-
1
tz.transition 2050, 3, :o4, 59277421, 24
-
1
tz.transition 2050, 10, :o3, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Bucharest
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Bucharest' do |tz|
-
1
tz.offset :o0, 6264, 0, :LMT
-
1
tz.offset :o1, 6264, 0, :BMT
-
1
tz.offset :o2, 7200, 0, :EET
-
1
tz.offset :o3, 7200, 3600, :EEST
-
-
1
tz.transition 1891, 9, :o1, 964802571, 400
-
1
tz.transition 1931, 7, :o2, 970618571, 400
-
1
tz.transition 1932, 5, :o3, 29122181, 12
-
1
tz.transition 1932, 10, :o2, 29123789, 12
-
1
tz.transition 1933, 4, :o3, 29125973, 12
-
1
tz.transition 1933, 9, :o2, 29128157, 12
-
1
tz.transition 1934, 4, :o3, 29130425, 12
-
1
tz.transition 1934, 10, :o2, 29132609, 12
-
1
tz.transition 1935, 4, :o3, 29134793, 12
-
1
tz.transition 1935, 10, :o2, 29136977, 12
-
1
tz.transition 1936, 4, :o3, 29139161, 12
-
1
tz.transition 1936, 10, :o2, 29141345, 12
-
1
tz.transition 1937, 4, :o3, 29143529, 12
-
1
tz.transition 1937, 10, :o2, 29145713, 12
-
1
tz.transition 1938, 4, :o3, 29147897, 12
-
1
tz.transition 1938, 10, :o2, 29150081, 12
-
1
tz.transition 1939, 4, :o3, 29152265, 12
-
1
tz.transition 1939, 9, :o2, 29154449, 12
-
1
tz.transition 1979, 5, :o3, 296604000
-
1
tz.transition 1979, 9, :o2, 307486800
-
1
tz.transition 1980, 4, :o3, 323816400
-
1
tz.transition 1980, 9, :o2, 338940000
-
1
tz.transition 1981, 3, :o3, 354672000
-
1
tz.transition 1981, 9, :o2, 370396800
-
1
tz.transition 1982, 3, :o3, 386121600
-
1
tz.transition 1982, 9, :o2, 401846400
-
1
tz.transition 1983, 3, :o3, 417571200
-
1
tz.transition 1983, 9, :o2, 433296000
-
1
tz.transition 1984, 3, :o3, 449020800
-
1
tz.transition 1984, 9, :o2, 465350400
-
1
tz.transition 1985, 3, :o3, 481075200
-
1
tz.transition 1985, 9, :o2, 496800000
-
1
tz.transition 1986, 3, :o3, 512524800
-
1
tz.transition 1986, 9, :o2, 528249600
-
1
tz.transition 1987, 3, :o3, 543974400
-
1
tz.transition 1987, 9, :o2, 559699200
-
1
tz.transition 1988, 3, :o3, 575424000
-
1
tz.transition 1988, 9, :o2, 591148800
-
1
tz.transition 1989, 3, :o3, 606873600
-
1
tz.transition 1989, 9, :o2, 622598400
-
1
tz.transition 1990, 3, :o3, 638323200
-
1
tz.transition 1990, 9, :o2, 654652800
-
1
tz.transition 1991, 3, :o3, 670370400
-
1
tz.transition 1991, 9, :o2, 686095200
-
1
tz.transition 1992, 3, :o3, 701820000
-
1
tz.transition 1992, 9, :o2, 717544800
-
1
tz.transition 1993, 3, :o3, 733269600
-
1
tz.transition 1993, 9, :o2, 748994400
-
1
tz.transition 1994, 3, :o3, 764719200
-
1
tz.transition 1994, 9, :o2, 780440400
-
1
tz.transition 1995, 3, :o3, 796168800
-
1
tz.transition 1995, 9, :o2, 811890000
-
1
tz.transition 1996, 3, :o3, 828223200
-
1
tz.transition 1996, 10, :o2, 846363600
-
1
tz.transition 1997, 3, :o3, 859683600
-
1
tz.transition 1997, 10, :o2, 877827600
-
1
tz.transition 1998, 3, :o3, 891133200
-
1
tz.transition 1998, 10, :o2, 909277200
-
1
tz.transition 1999, 3, :o3, 922582800
-
1
tz.transition 1999, 10, :o2, 941331600
-
1
tz.transition 2000, 3, :o3, 954032400
-
1
tz.transition 2000, 10, :o2, 972781200
-
1
tz.transition 2001, 3, :o3, 985482000
-
1
tz.transition 2001, 10, :o2, 1004230800
-
1
tz.transition 2002, 3, :o3, 1017536400
-
1
tz.transition 2002, 10, :o2, 1035680400
-
1
tz.transition 2003, 3, :o3, 1048986000
-
1
tz.transition 2003, 10, :o2, 1067130000
-
1
tz.transition 2004, 3, :o3, 1080435600
-
1
tz.transition 2004, 10, :o2, 1099184400
-
1
tz.transition 2005, 3, :o3, 1111885200
-
1
tz.transition 2005, 10, :o2, 1130634000
-
1
tz.transition 2006, 3, :o3, 1143334800
-
1
tz.transition 2006, 10, :o2, 1162083600
-
1
tz.transition 2007, 3, :o3, 1174784400
-
1
tz.transition 2007, 10, :o2, 1193533200
-
1
tz.transition 2008, 3, :o3, 1206838800
-
1
tz.transition 2008, 10, :o2, 1224982800
-
1
tz.transition 2009, 3, :o3, 1238288400
-
1
tz.transition 2009, 10, :o2, 1256432400
-
1
tz.transition 2010, 3, :o3, 1269738000
-
1
tz.transition 2010, 10, :o2, 1288486800
-
1
tz.transition 2011, 3, :o3, 1301187600
-
1
tz.transition 2011, 10, :o2, 1319936400
-
1
tz.transition 2012, 3, :o3, 1332637200
-
1
tz.transition 2012, 10, :o2, 1351386000
-
1
tz.transition 2013, 3, :o3, 1364691600
-
1
tz.transition 2013, 10, :o2, 1382835600
-
1
tz.transition 2014, 3, :o3, 1396141200
-
1
tz.transition 2014, 10, :o2, 1414285200
-
1
tz.transition 2015, 3, :o3, 1427590800
-
1
tz.transition 2015, 10, :o2, 1445734800
-
1
tz.transition 2016, 3, :o3, 1459040400
-
1
tz.transition 2016, 10, :o2, 1477789200
-
1
tz.transition 2017, 3, :o3, 1490490000
-
1
tz.transition 2017, 10, :o2, 1509238800
-
1
tz.transition 2018, 3, :o3, 1521939600
-
1
tz.transition 2018, 10, :o2, 1540688400
-
1
tz.transition 2019, 3, :o3, 1553994000
-
1
tz.transition 2019, 10, :o2, 1572138000
-
1
tz.transition 2020, 3, :o3, 1585443600
-
1
tz.transition 2020, 10, :o2, 1603587600
-
1
tz.transition 2021, 3, :o3, 1616893200
-
1
tz.transition 2021, 10, :o2, 1635642000
-
1
tz.transition 2022, 3, :o3, 1648342800
-
1
tz.transition 2022, 10, :o2, 1667091600
-
1
tz.transition 2023, 3, :o3, 1679792400
-
1
tz.transition 2023, 10, :o2, 1698541200
-
1
tz.transition 2024, 3, :o3, 1711846800
-
1
tz.transition 2024, 10, :o2, 1729990800
-
1
tz.transition 2025, 3, :o3, 1743296400
-
1
tz.transition 2025, 10, :o2, 1761440400
-
1
tz.transition 2026, 3, :o3, 1774746000
-
1
tz.transition 2026, 10, :o2, 1792890000
-
1
tz.transition 2027, 3, :o3, 1806195600
-
1
tz.transition 2027, 10, :o2, 1824944400
-
1
tz.transition 2028, 3, :o3, 1837645200
-
1
tz.transition 2028, 10, :o2, 1856394000
-
1
tz.transition 2029, 3, :o3, 1869094800
-
1
tz.transition 2029, 10, :o2, 1887843600
-
1
tz.transition 2030, 3, :o3, 1901149200
-
1
tz.transition 2030, 10, :o2, 1919293200
-
1
tz.transition 2031, 3, :o3, 1932598800
-
1
tz.transition 2031, 10, :o2, 1950742800
-
1
tz.transition 2032, 3, :o3, 1964048400
-
1
tz.transition 2032, 10, :o2, 1982797200
-
1
tz.transition 2033, 3, :o3, 1995498000
-
1
tz.transition 2033, 10, :o2, 2014246800
-
1
tz.transition 2034, 3, :o3, 2026947600
-
1
tz.transition 2034, 10, :o2, 2045696400
-
1
tz.transition 2035, 3, :o3, 2058397200
-
1
tz.transition 2035, 10, :o2, 2077146000
-
1
tz.transition 2036, 3, :o3, 2090451600
-
1
tz.transition 2036, 10, :o2, 2108595600
-
1
tz.transition 2037, 3, :o3, 2121901200
-
1
tz.transition 2037, 10, :o2, 2140045200
-
1
tz.transition 2038, 3, :o3, 59172253, 24
-
1
tz.transition 2038, 10, :o2, 59177461, 24
-
1
tz.transition 2039, 3, :o3, 59180989, 24
-
1
tz.transition 2039, 10, :o2, 59186197, 24
-
1
tz.transition 2040, 3, :o3, 59189725, 24
-
1
tz.transition 2040, 10, :o2, 59194933, 24
-
1
tz.transition 2041, 3, :o3, 59198629, 24
-
1
tz.transition 2041, 10, :o2, 59203669, 24
-
1
tz.transition 2042, 3, :o3, 59207365, 24
-
1
tz.transition 2042, 10, :o2, 59212405, 24
-
1
tz.transition 2043, 3, :o3, 59216101, 24
-
1
tz.transition 2043, 10, :o2, 59221141, 24
-
1
tz.transition 2044, 3, :o3, 59224837, 24
-
1
tz.transition 2044, 10, :o2, 59230045, 24
-
1
tz.transition 2045, 3, :o3, 59233573, 24
-
1
tz.transition 2045, 10, :o2, 59238781, 24
-
1
tz.transition 2046, 3, :o3, 59242309, 24
-
1
tz.transition 2046, 10, :o2, 59247517, 24
-
1
tz.transition 2047, 3, :o3, 59251213, 24
-
1
tz.transition 2047, 10, :o2, 59256253, 24
-
1
tz.transition 2048, 3, :o3, 59259949, 24
-
1
tz.transition 2048, 10, :o2, 59264989, 24
-
1
tz.transition 2049, 3, :o3, 59268685, 24
-
1
tz.transition 2049, 10, :o2, 59273893, 24
-
1
tz.transition 2050, 3, :o3, 59277421, 24
-
1
tz.transition 2050, 10, :o2, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Budapest
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Budapest' do |tz|
-
1
tz.offset :o0, 4580, 0, :LMT
-
1
tz.offset :o1, 3600, 0, :CET
-
1
tz.offset :o2, 3600, 3600, :CEST
-
-
1
tz.transition 1890, 9, :o1, 10418291051, 4320
-
1
tz.transition 1916, 4, :o2, 29051813, 12
-
1
tz.transition 1916, 9, :o1, 58107299, 24
-
1
tz.transition 1917, 4, :o2, 58112029, 24
-
1
tz.transition 1917, 9, :o1, 58115725, 24
-
1
tz.transition 1918, 4, :o2, 29060215, 12
-
1
tz.transition 1918, 9, :o1, 58124773, 24
-
1
tz.transition 1919, 4, :o2, 29064763, 12
-
1
tz.transition 1919, 9, :o1, 58133197, 24
-
1
tz.transition 1920, 4, :o2, 29069035, 12
-
1
tz.transition 1920, 9, :o1, 58142341, 24
-
1
tz.transition 1941, 4, :o2, 58322173, 24
-
1
tz.transition 1942, 11, :o1, 58335973, 24
-
1
tz.transition 1943, 3, :o2, 58339501, 24
-
1
tz.transition 1943, 10, :o1, 58344037, 24
-
1
tz.transition 1944, 4, :o2, 58348405, 24
-
1
tz.transition 1944, 10, :o1, 58352773, 24
-
1
tz.transition 1945, 5, :o2, 29178929, 12
-
1
tz.transition 1945, 11, :o1, 29181149, 12
-
1
tz.transition 1946, 3, :o2, 58365853, 24
-
1
tz.transition 1946, 10, :o1, 58370389, 24
-
1
tz.transition 1947, 4, :o2, 58374757, 24
-
1
tz.transition 1947, 10, :o1, 58379125, 24
-
1
tz.transition 1948, 4, :o2, 58383493, 24
-
1
tz.transition 1948, 10, :o1, 58387861, 24
-
1
tz.transition 1949, 4, :o2, 58392397, 24
-
1
tz.transition 1949, 10, :o1, 58396597, 24
-
1
tz.transition 1950, 4, :o2, 58401325, 24
-
1
tz.transition 1950, 10, :o1, 58405861, 24
-
1
tz.transition 1954, 5, :o2, 58437251, 24
-
1
tz.transition 1954, 10, :o1, 29220221, 12
-
1
tz.transition 1955, 5, :o2, 58446011, 24
-
1
tz.transition 1955, 10, :o1, 29224601, 12
-
1
tz.transition 1956, 6, :o2, 58455059, 24
-
1
tz.transition 1956, 9, :o1, 29228957, 12
-
1
tz.transition 1957, 6, :o2, 4871983, 2
-
1
tz.transition 1957, 9, :o1, 58466653, 24
-
1
tz.transition 1980, 4, :o2, 323827200
-
1
tz.transition 1980, 9, :o1, 338950800
-
1
tz.transition 1981, 3, :o2, 354675600
-
1
tz.transition 1981, 9, :o1, 370400400
-
1
tz.transition 1982, 3, :o2, 386125200
-
1
tz.transition 1982, 9, :o1, 401850000
-
1
tz.transition 1983, 3, :o2, 417574800
-
1
tz.transition 1983, 9, :o1, 433299600
-
1
tz.transition 1984, 3, :o2, 449024400
-
1
tz.transition 1984, 9, :o1, 465354000
-
1
tz.transition 1985, 3, :o2, 481078800
-
1
tz.transition 1985, 9, :o1, 496803600
-
1
tz.transition 1986, 3, :o2, 512528400
-
1
tz.transition 1986, 9, :o1, 528253200
-
1
tz.transition 1987, 3, :o2, 543978000
-
1
tz.transition 1987, 9, :o1, 559702800
-
1
tz.transition 1988, 3, :o2, 575427600
-
1
tz.transition 1988, 9, :o1, 591152400
-
1
tz.transition 1989, 3, :o2, 606877200
-
1
tz.transition 1989, 9, :o1, 622602000
-
1
tz.transition 1990, 3, :o2, 638326800
-
1
tz.transition 1990, 9, :o1, 654656400
-
1
tz.transition 1991, 3, :o2, 670381200
-
1
tz.transition 1991, 9, :o1, 686106000
-
1
tz.transition 1992, 3, :o2, 701830800
-
1
tz.transition 1992, 9, :o1, 717555600
-
1
tz.transition 1993, 3, :o2, 733280400
-
1
tz.transition 1993, 9, :o1, 749005200
-
1
tz.transition 1994, 3, :o2, 764730000
-
1
tz.transition 1994, 9, :o1, 780454800
-
1
tz.transition 1995, 3, :o2, 796179600
-
1
tz.transition 1995, 9, :o1, 811904400
-
1
tz.transition 1996, 3, :o2, 828234000
-
1
tz.transition 1996, 10, :o1, 846378000
-
1
tz.transition 1997, 3, :o2, 859683600
-
1
tz.transition 1997, 10, :o1, 877827600
-
1
tz.transition 1998, 3, :o2, 891133200
-
1
tz.transition 1998, 10, :o1, 909277200
-
1
tz.transition 1999, 3, :o2, 922582800
-
1
tz.transition 1999, 10, :o1, 941331600
-
1
tz.transition 2000, 3, :o2, 954032400
-
1
tz.transition 2000, 10, :o1, 972781200
-
1
tz.transition 2001, 3, :o2, 985482000
-
1
tz.transition 2001, 10, :o1, 1004230800
-
1
tz.transition 2002, 3, :o2, 1017536400
-
1
tz.transition 2002, 10, :o1, 1035680400
-
1
tz.transition 2003, 3, :o2, 1048986000
-
1
tz.transition 2003, 10, :o1, 1067130000
-
1
tz.transition 2004, 3, :o2, 1080435600
-
1
tz.transition 2004, 10, :o1, 1099184400
-
1
tz.transition 2005, 3, :o2, 1111885200
-
1
tz.transition 2005, 10, :o1, 1130634000
-
1
tz.transition 2006, 3, :o2, 1143334800
-
1
tz.transition 2006, 10, :o1, 1162083600
-
1
tz.transition 2007, 3, :o2, 1174784400
-
1
tz.transition 2007, 10, :o1, 1193533200
-
1
tz.transition 2008, 3, :o2, 1206838800
-
1
tz.transition 2008, 10, :o1, 1224982800
-
1
tz.transition 2009, 3, :o2, 1238288400
-
1
tz.transition 2009, 10, :o1, 1256432400
-
1
tz.transition 2010, 3, :o2, 1269738000
-
1
tz.transition 2010, 10, :o1, 1288486800
-
1
tz.transition 2011, 3, :o2, 1301187600
-
1
tz.transition 2011, 10, :o1, 1319936400
-
1
tz.transition 2012, 3, :o2, 1332637200
-
1
tz.transition 2012, 10, :o1, 1351386000
-
1
tz.transition 2013, 3, :o2, 1364691600
-
1
tz.transition 2013, 10, :o1, 1382835600
-
1
tz.transition 2014, 3, :o2, 1396141200
-
1
tz.transition 2014, 10, :o1, 1414285200
-
1
tz.transition 2015, 3, :o2, 1427590800
-
1
tz.transition 2015, 10, :o1, 1445734800
-
1
tz.transition 2016, 3, :o2, 1459040400
-
1
tz.transition 2016, 10, :o1, 1477789200
-
1
tz.transition 2017, 3, :o2, 1490490000
-
1
tz.transition 2017, 10, :o1, 1509238800
-
1
tz.transition 2018, 3, :o2, 1521939600
-
1
tz.transition 2018, 10, :o1, 1540688400
-
1
tz.transition 2019, 3, :o2, 1553994000
-
1
tz.transition 2019, 10, :o1, 1572138000
-
1
tz.transition 2020, 3, :o2, 1585443600
-
1
tz.transition 2020, 10, :o1, 1603587600
-
1
tz.transition 2021, 3, :o2, 1616893200
-
1
tz.transition 2021, 10, :o1, 1635642000
-
1
tz.transition 2022, 3, :o2, 1648342800
-
1
tz.transition 2022, 10, :o1, 1667091600
-
1
tz.transition 2023, 3, :o2, 1679792400
-
1
tz.transition 2023, 10, :o1, 1698541200
-
1
tz.transition 2024, 3, :o2, 1711846800
-
1
tz.transition 2024, 10, :o1, 1729990800
-
1
tz.transition 2025, 3, :o2, 1743296400
-
1
tz.transition 2025, 10, :o1, 1761440400
-
1
tz.transition 2026, 3, :o2, 1774746000
-
1
tz.transition 2026, 10, :o1, 1792890000
-
1
tz.transition 2027, 3, :o2, 1806195600
-
1
tz.transition 2027, 10, :o1, 1824944400
-
1
tz.transition 2028, 3, :o2, 1837645200
-
1
tz.transition 2028, 10, :o1, 1856394000
-
1
tz.transition 2029, 3, :o2, 1869094800
-
1
tz.transition 2029, 10, :o1, 1887843600
-
1
tz.transition 2030, 3, :o2, 1901149200
-
1
tz.transition 2030, 10, :o1, 1919293200
-
1
tz.transition 2031, 3, :o2, 1932598800
-
1
tz.transition 2031, 10, :o1, 1950742800
-
1
tz.transition 2032, 3, :o2, 1964048400
-
1
tz.transition 2032, 10, :o1, 1982797200
-
1
tz.transition 2033, 3, :o2, 1995498000
-
1
tz.transition 2033, 10, :o1, 2014246800
-
1
tz.transition 2034, 3, :o2, 2026947600
-
1
tz.transition 2034, 10, :o1, 2045696400
-
1
tz.transition 2035, 3, :o2, 2058397200
-
1
tz.transition 2035, 10, :o1, 2077146000
-
1
tz.transition 2036, 3, :o2, 2090451600
-
1
tz.transition 2036, 10, :o1, 2108595600
-
1
tz.transition 2037, 3, :o2, 2121901200
-
1
tz.transition 2037, 10, :o1, 2140045200
-
1
tz.transition 2038, 3, :o2, 59172253, 24
-
1
tz.transition 2038, 10, :o1, 59177461, 24
-
1
tz.transition 2039, 3, :o2, 59180989, 24
-
1
tz.transition 2039, 10, :o1, 59186197, 24
-
1
tz.transition 2040, 3, :o2, 59189725, 24
-
1
tz.transition 2040, 10, :o1, 59194933, 24
-
1
tz.transition 2041, 3, :o2, 59198629, 24
-
1
tz.transition 2041, 10, :o1, 59203669, 24
-
1
tz.transition 2042, 3, :o2, 59207365, 24
-
1
tz.transition 2042, 10, :o1, 59212405, 24
-
1
tz.transition 2043, 3, :o2, 59216101, 24
-
1
tz.transition 2043, 10, :o1, 59221141, 24
-
1
tz.transition 2044, 3, :o2, 59224837, 24
-
1
tz.transition 2044, 10, :o1, 59230045, 24
-
1
tz.transition 2045, 3, :o2, 59233573, 24
-
1
tz.transition 2045, 10, :o1, 59238781, 24
-
1
tz.transition 2046, 3, :o2, 59242309, 24
-
1
tz.transition 2046, 10, :o1, 59247517, 24
-
1
tz.transition 2047, 3, :o2, 59251213, 24
-
1
tz.transition 2047, 10, :o1, 59256253, 24
-
1
tz.transition 2048, 3, :o2, 59259949, 24
-
1
tz.transition 2048, 10, :o1, 59264989, 24
-
1
tz.transition 2049, 3, :o2, 59268685, 24
-
1
tz.transition 2049, 10, :o1, 59273893, 24
-
1
tz.transition 2050, 3, :o2, 59277421, 24
-
1
tz.transition 2050, 10, :o1, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Copenhagen
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Copenhagen' do |tz|
-
1
tz.offset :o0, 3020, 0, :LMT
-
1
tz.offset :o1, 3020, 0, :CMT
-
1
tz.offset :o2, 3600, 0, :CET
-
1
tz.offset :o3, 3600, 3600, :CEST
-
-
1
tz.transition 1889, 12, :o1, 10417111769, 4320
-
1
tz.transition 1893, 12, :o2, 10423423289, 4320
-
1
tz.transition 1916, 5, :o3, 29051981, 12
-
1
tz.transition 1916, 9, :o2, 19369099, 8
-
1
tz.transition 1940, 5, :o3, 58314347, 24
-
1
tz.transition 1942, 11, :o2, 58335973, 24
-
1
tz.transition 1943, 3, :o3, 58339501, 24
-
1
tz.transition 1943, 10, :o2, 58344037, 24
-
1
tz.transition 1944, 4, :o3, 58348405, 24
-
1
tz.transition 1944, 10, :o2, 58352773, 24
-
1
tz.transition 1945, 4, :o3, 58357141, 24
-
1
tz.transition 1945, 8, :o2, 58360381, 24
-
1
tz.transition 1946, 5, :o3, 58366597, 24
-
1
tz.transition 1946, 9, :o2, 58369549, 24
-
1
tz.transition 1947, 5, :o3, 58375429, 24
-
1
tz.transition 1947, 8, :o2, 58377781, 24
-
1
tz.transition 1948, 5, :o3, 58384333, 24
-
1
tz.transition 1948, 8, :o2, 58386517, 24
-
1
tz.transition 1980, 4, :o3, 323830800
-
1
tz.transition 1980, 9, :o2, 338950800
-
1
tz.transition 1981, 3, :o3, 354675600
-
1
tz.transition 1981, 9, :o2, 370400400
-
1
tz.transition 1982, 3, :o3, 386125200
-
1
tz.transition 1982, 9, :o2, 401850000
-
1
tz.transition 1983, 3, :o3, 417574800
-
1
tz.transition 1983, 9, :o2, 433299600
-
1
tz.transition 1984, 3, :o3, 449024400
-
1
tz.transition 1984, 9, :o2, 465354000
-
1
tz.transition 1985, 3, :o3, 481078800
-
1
tz.transition 1985, 9, :o2, 496803600
-
1
tz.transition 1986, 3, :o3, 512528400
-
1
tz.transition 1986, 9, :o2, 528253200
-
1
tz.transition 1987, 3, :o3, 543978000
-
1
tz.transition 1987, 9, :o2, 559702800
-
1
tz.transition 1988, 3, :o3, 575427600
-
1
tz.transition 1988, 9, :o2, 591152400
-
1
tz.transition 1989, 3, :o3, 606877200
-
1
tz.transition 1989, 9, :o2, 622602000
-
1
tz.transition 1990, 3, :o3, 638326800
-
1
tz.transition 1990, 9, :o2, 654656400
-
1
tz.transition 1991, 3, :o3, 670381200
-
1
tz.transition 1991, 9, :o2, 686106000
-
1
tz.transition 1992, 3, :o3, 701830800
-
1
tz.transition 1992, 9, :o2, 717555600
-
1
tz.transition 1993, 3, :o3, 733280400
-
1
tz.transition 1993, 9, :o2, 749005200
-
1
tz.transition 1994, 3, :o3, 764730000
-
1
tz.transition 1994, 9, :o2, 780454800
-
1
tz.transition 1995, 3, :o3, 796179600
-
1
tz.transition 1995, 9, :o2, 811904400
-
1
tz.transition 1996, 3, :o3, 828234000
-
1
tz.transition 1996, 10, :o2, 846378000
-
1
tz.transition 1997, 3, :o3, 859683600
-
1
tz.transition 1997, 10, :o2, 877827600
-
1
tz.transition 1998, 3, :o3, 891133200
-
1
tz.transition 1998, 10, :o2, 909277200
-
1
tz.transition 1999, 3, :o3, 922582800
-
1
tz.transition 1999, 10, :o2, 941331600
-
1
tz.transition 2000, 3, :o3, 954032400
-
1
tz.transition 2000, 10, :o2, 972781200
-
1
tz.transition 2001, 3, :o3, 985482000
-
1
tz.transition 2001, 10, :o2, 1004230800
-
1
tz.transition 2002, 3, :o3, 1017536400
-
1
tz.transition 2002, 10, :o2, 1035680400
-
1
tz.transition 2003, 3, :o3, 1048986000
-
1
tz.transition 2003, 10, :o2, 1067130000
-
1
tz.transition 2004, 3, :o3, 1080435600
-
1
tz.transition 2004, 10, :o2, 1099184400
-
1
tz.transition 2005, 3, :o3, 1111885200
-
1
tz.transition 2005, 10, :o2, 1130634000
-
1
tz.transition 2006, 3, :o3, 1143334800
-
1
tz.transition 2006, 10, :o2, 1162083600
-
1
tz.transition 2007, 3, :o3, 1174784400
-
1
tz.transition 2007, 10, :o2, 1193533200
-
1
tz.transition 2008, 3, :o3, 1206838800
-
1
tz.transition 2008, 10, :o2, 1224982800
-
1
tz.transition 2009, 3, :o3, 1238288400
-
1
tz.transition 2009, 10, :o2, 1256432400
-
1
tz.transition 2010, 3, :o3, 1269738000
-
1
tz.transition 2010, 10, :o2, 1288486800
-
1
tz.transition 2011, 3, :o3, 1301187600
-
1
tz.transition 2011, 10, :o2, 1319936400
-
1
tz.transition 2012, 3, :o3, 1332637200
-
1
tz.transition 2012, 10, :o2, 1351386000
-
1
tz.transition 2013, 3, :o3, 1364691600
-
1
tz.transition 2013, 10, :o2, 1382835600
-
1
tz.transition 2014, 3, :o3, 1396141200
-
1
tz.transition 2014, 10, :o2, 1414285200
-
1
tz.transition 2015, 3, :o3, 1427590800
-
1
tz.transition 2015, 10, :o2, 1445734800
-
1
tz.transition 2016, 3, :o3, 1459040400
-
1
tz.transition 2016, 10, :o2, 1477789200
-
1
tz.transition 2017, 3, :o3, 1490490000
-
1
tz.transition 2017, 10, :o2, 1509238800
-
1
tz.transition 2018, 3, :o3, 1521939600
-
1
tz.transition 2018, 10, :o2, 1540688400
-
1
tz.transition 2019, 3, :o3, 1553994000
-
1
tz.transition 2019, 10, :o2, 1572138000
-
1
tz.transition 2020, 3, :o3, 1585443600
-
1
tz.transition 2020, 10, :o2, 1603587600
-
1
tz.transition 2021, 3, :o3, 1616893200
-
1
tz.transition 2021, 10, :o2, 1635642000
-
1
tz.transition 2022, 3, :o3, 1648342800
-
1
tz.transition 2022, 10, :o2, 1667091600
-
1
tz.transition 2023, 3, :o3, 1679792400
-
1
tz.transition 2023, 10, :o2, 1698541200
-
1
tz.transition 2024, 3, :o3, 1711846800
-
1
tz.transition 2024, 10, :o2, 1729990800
-
1
tz.transition 2025, 3, :o3, 1743296400
-
1
tz.transition 2025, 10, :o2, 1761440400
-
1
tz.transition 2026, 3, :o3, 1774746000
-
1
tz.transition 2026, 10, :o2, 1792890000
-
1
tz.transition 2027, 3, :o3, 1806195600
-
1
tz.transition 2027, 10, :o2, 1824944400
-
1
tz.transition 2028, 3, :o3, 1837645200
-
1
tz.transition 2028, 10, :o2, 1856394000
-
1
tz.transition 2029, 3, :o3, 1869094800
-
1
tz.transition 2029, 10, :o2, 1887843600
-
1
tz.transition 2030, 3, :o3, 1901149200
-
1
tz.transition 2030, 10, :o2, 1919293200
-
1
tz.transition 2031, 3, :o3, 1932598800
-
1
tz.transition 2031, 10, :o2, 1950742800
-
1
tz.transition 2032, 3, :o3, 1964048400
-
1
tz.transition 2032, 10, :o2, 1982797200
-
1
tz.transition 2033, 3, :o3, 1995498000
-
1
tz.transition 2033, 10, :o2, 2014246800
-
1
tz.transition 2034, 3, :o3, 2026947600
-
1
tz.transition 2034, 10, :o2, 2045696400
-
1
tz.transition 2035, 3, :o3, 2058397200
-
1
tz.transition 2035, 10, :o2, 2077146000
-
1
tz.transition 2036, 3, :o3, 2090451600
-
1
tz.transition 2036, 10, :o2, 2108595600
-
1
tz.transition 2037, 3, :o3, 2121901200
-
1
tz.transition 2037, 10, :o2, 2140045200
-
1
tz.transition 2038, 3, :o3, 59172253, 24
-
1
tz.transition 2038, 10, :o2, 59177461, 24
-
1
tz.transition 2039, 3, :o3, 59180989, 24
-
1
tz.transition 2039, 10, :o2, 59186197, 24
-
1
tz.transition 2040, 3, :o3, 59189725, 24
-
1
tz.transition 2040, 10, :o2, 59194933, 24
-
1
tz.transition 2041, 3, :o3, 59198629, 24
-
1
tz.transition 2041, 10, :o2, 59203669, 24
-
1
tz.transition 2042, 3, :o3, 59207365, 24
-
1
tz.transition 2042, 10, :o2, 59212405, 24
-
1
tz.transition 2043, 3, :o3, 59216101, 24
-
1
tz.transition 2043, 10, :o2, 59221141, 24
-
1
tz.transition 2044, 3, :o3, 59224837, 24
-
1
tz.transition 2044, 10, :o2, 59230045, 24
-
1
tz.transition 2045, 3, :o3, 59233573, 24
-
1
tz.transition 2045, 10, :o2, 59238781, 24
-
1
tz.transition 2046, 3, :o3, 59242309, 24
-
1
tz.transition 2046, 10, :o2, 59247517, 24
-
1
tz.transition 2047, 3, :o3, 59251213, 24
-
1
tz.transition 2047, 10, :o2, 59256253, 24
-
1
tz.transition 2048, 3, :o3, 59259949, 24
-
1
tz.transition 2048, 10, :o2, 59264989, 24
-
1
tz.transition 2049, 3, :o3, 59268685, 24
-
1
tz.transition 2049, 10, :o2, 59273893, 24
-
1
tz.transition 2050, 3, :o3, 59277421, 24
-
1
tz.transition 2050, 10, :o2, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Dublin
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Dublin' do |tz|
-
1
tz.offset :o0, -1500, 0, :LMT
-
1
tz.offset :o1, -1521, 0, :DMT
-
1
tz.offset :o2, -1521, 3600, :IST
-
1
tz.offset :o3, 0, 0, :GMT
-
1
tz.offset :o4, 0, 3600, :BST
-
1
tz.offset :o5, 0, 3600, :IST
-
1
tz.offset :o6, 3600, 0, :IST
-
-
1
tz.transition 1880, 8, :o1, 693483701, 288
-
1
tz.transition 1916, 5, :o2, 7747214723, 3200
-
1
tz.transition 1916, 10, :o3, 7747640323, 3200
-
1
tz.transition 1917, 4, :o4, 29055919, 12
-
1
tz.transition 1917, 9, :o3, 29057863, 12
-
1
tz.transition 1918, 3, :o4, 29060119, 12
-
1
tz.transition 1918, 9, :o3, 29062399, 12
-
1
tz.transition 1919, 3, :o4, 29064571, 12
-
1
tz.transition 1919, 9, :o3, 29066767, 12
-
1
tz.transition 1920, 3, :o4, 29068939, 12
-
1
tz.transition 1920, 10, :o3, 29071471, 12
-
1
tz.transition 1921, 4, :o4, 29073391, 12
-
1
tz.transition 1921, 10, :o3, 29075587, 12
-
1
tz.transition 1922, 3, :o5, 29077675, 12
-
1
tz.transition 1922, 10, :o3, 29080027, 12
-
1
tz.transition 1923, 4, :o5, 29082379, 12
-
1
tz.transition 1923, 9, :o3, 29084143, 12
-
1
tz.transition 1924, 4, :o5, 29086663, 12
-
1
tz.transition 1924, 9, :o3, 29088595, 12
-
1
tz.transition 1925, 4, :o5, 29091115, 12
-
1
tz.transition 1925, 10, :o3, 29093131, 12
-
1
tz.transition 1926, 4, :o5, 29095483, 12
-
1
tz.transition 1926, 10, :o3, 29097499, 12
-
1
tz.transition 1927, 4, :o5, 29099767, 12
-
1
tz.transition 1927, 10, :o3, 29101867, 12
-
1
tz.transition 1928, 4, :o5, 29104303, 12
-
1
tz.transition 1928, 10, :o3, 29106319, 12
-
1
tz.transition 1929, 4, :o5, 29108671, 12
-
1
tz.transition 1929, 10, :o3, 29110687, 12
-
1
tz.transition 1930, 4, :o5, 29112955, 12
-
1
tz.transition 1930, 10, :o3, 29115055, 12
-
1
tz.transition 1931, 4, :o5, 29117407, 12
-
1
tz.transition 1931, 10, :o3, 29119423, 12
-
1
tz.transition 1932, 4, :o5, 29121775, 12
-
1
tz.transition 1932, 10, :o3, 29123791, 12
-
1
tz.transition 1933, 4, :o5, 29126059, 12
-
1
tz.transition 1933, 10, :o3, 29128243, 12
-
1
tz.transition 1934, 4, :o5, 29130595, 12
-
1
tz.transition 1934, 10, :o3, 29132611, 12
-
1
tz.transition 1935, 4, :o5, 29134879, 12
-
1
tz.transition 1935, 10, :o3, 29136979, 12
-
1
tz.transition 1936, 4, :o5, 29139331, 12
-
1
tz.transition 1936, 10, :o3, 29141347, 12
-
1
tz.transition 1937, 4, :o5, 29143699, 12
-
1
tz.transition 1937, 10, :o3, 29145715, 12
-
1
tz.transition 1938, 4, :o5, 29147983, 12
-
1
tz.transition 1938, 10, :o3, 29150083, 12
-
1
tz.transition 1939, 4, :o5, 29152435, 12
-
1
tz.transition 1939, 11, :o3, 29155039, 12
-
1
tz.transition 1940, 2, :o5, 29156215, 12
-
1
tz.transition 1946, 10, :o3, 58370389, 24
-
1
tz.transition 1947, 3, :o5, 29187127, 12
-
1
tz.transition 1947, 11, :o3, 58379797, 24
-
1
tz.transition 1948, 4, :o5, 29191915, 12
-
1
tz.transition 1948, 10, :o3, 29194267, 12
-
1
tz.transition 1949, 4, :o5, 29196115, 12
-
1
tz.transition 1949, 10, :o3, 29198635, 12
-
1
tz.transition 1950, 4, :o5, 29200651, 12
-
1
tz.transition 1950, 10, :o3, 29202919, 12
-
1
tz.transition 1951, 4, :o5, 29205019, 12
-
1
tz.transition 1951, 10, :o3, 29207287, 12
-
1
tz.transition 1952, 4, :o5, 29209471, 12
-
1
tz.transition 1952, 10, :o3, 29211739, 12
-
1
tz.transition 1953, 4, :o5, 29213839, 12
-
1
tz.transition 1953, 10, :o3, 29215855, 12
-
1
tz.transition 1954, 4, :o5, 29218123, 12
-
1
tz.transition 1954, 10, :o3, 29220223, 12
-
1
tz.transition 1955, 4, :o5, 29222575, 12
-
1
tz.transition 1955, 10, :o3, 29224591, 12
-
1
tz.transition 1956, 4, :o5, 29227027, 12
-
1
tz.transition 1956, 10, :o3, 29229043, 12
-
1
tz.transition 1957, 4, :o5, 29231311, 12
-
1
tz.transition 1957, 10, :o3, 29233411, 12
-
1
tz.transition 1958, 4, :o5, 29235763, 12
-
1
tz.transition 1958, 10, :o3, 29237779, 12
-
1
tz.transition 1959, 4, :o5, 29240131, 12
-
1
tz.transition 1959, 10, :o3, 29242147, 12
-
1
tz.transition 1960, 4, :o5, 29244415, 12
-
1
tz.transition 1960, 10, :o3, 29246515, 12
-
1
tz.transition 1961, 3, :o5, 29248615, 12
-
1
tz.transition 1961, 10, :o3, 29251219, 12
-
1
tz.transition 1962, 3, :o5, 29252983, 12
-
1
tz.transition 1962, 10, :o3, 29255587, 12
-
1
tz.transition 1963, 3, :o5, 29257435, 12
-
1
tz.transition 1963, 10, :o3, 29259955, 12
-
1
tz.transition 1964, 3, :o5, 29261719, 12
-
1
tz.transition 1964, 10, :o3, 29264323, 12
-
1
tz.transition 1965, 3, :o5, 29266087, 12
-
1
tz.transition 1965, 10, :o3, 29268691, 12
-
1
tz.transition 1966, 3, :o5, 29270455, 12
-
1
tz.transition 1966, 10, :o3, 29273059, 12
-
1
tz.transition 1967, 3, :o5, 29274823, 12
-
1
tz.transition 1967, 10, :o3, 29277511, 12
-
1
tz.transition 1968, 2, :o5, 29278855, 12
-
1
tz.transition 1968, 10, :o6, 58563755, 24
-
1
tz.transition 1971, 10, :o3, 57722400
-
1
tz.transition 1972, 3, :o5, 69818400
-
1
tz.transition 1972, 10, :o3, 89172000
-
1
tz.transition 1973, 3, :o5, 101268000
-
1
tz.transition 1973, 10, :o3, 120621600
-
1
tz.transition 1974, 3, :o5, 132717600
-
1
tz.transition 1974, 10, :o3, 152071200
-
1
tz.transition 1975, 3, :o5, 164167200
-
1
tz.transition 1975, 10, :o3, 183520800
-
1
tz.transition 1976, 3, :o5, 196221600
-
1
tz.transition 1976, 10, :o3, 214970400
-
1
tz.transition 1977, 3, :o5, 227671200
-
1
tz.transition 1977, 10, :o3, 246420000
-
1
tz.transition 1978, 3, :o5, 259120800
-
1
tz.transition 1978, 10, :o3, 278474400
-
1
tz.transition 1979, 3, :o5, 290570400
-
1
tz.transition 1979, 10, :o3, 309924000
-
1
tz.transition 1980, 3, :o5, 322020000
-
1
tz.transition 1980, 10, :o3, 341373600
-
1
tz.transition 1981, 3, :o5, 354675600
-
1
tz.transition 1981, 10, :o3, 372819600
-
1
tz.transition 1982, 3, :o5, 386125200
-
1
tz.transition 1982, 10, :o3, 404269200
-
1
tz.transition 1983, 3, :o5, 417574800
-
1
tz.transition 1983, 10, :o3, 435718800
-
1
tz.transition 1984, 3, :o5, 449024400
-
1
tz.transition 1984, 10, :o3, 467773200
-
1
tz.transition 1985, 3, :o5, 481078800
-
1
tz.transition 1985, 10, :o3, 499222800
-
1
tz.transition 1986, 3, :o5, 512528400
-
1
tz.transition 1986, 10, :o3, 530672400
-
1
tz.transition 1987, 3, :o5, 543978000
-
1
tz.transition 1987, 10, :o3, 562122000
-
1
tz.transition 1988, 3, :o5, 575427600
-
1
tz.transition 1988, 10, :o3, 593571600
-
1
tz.transition 1989, 3, :o5, 606877200
-
1
tz.transition 1989, 10, :o3, 625626000
-
1
tz.transition 1990, 3, :o5, 638326800
-
1
tz.transition 1990, 10, :o3, 657075600
-
1
tz.transition 1991, 3, :o5, 670381200
-
1
tz.transition 1991, 10, :o3, 688525200
-
1
tz.transition 1992, 3, :o5, 701830800
-
1
tz.transition 1992, 10, :o3, 719974800
-
1
tz.transition 1993, 3, :o5, 733280400
-
1
tz.transition 1993, 10, :o3, 751424400
-
1
tz.transition 1994, 3, :o5, 764730000
-
1
tz.transition 1994, 10, :o3, 782874000
-
1
tz.transition 1995, 3, :o5, 796179600
-
1
tz.transition 1995, 10, :o3, 814323600
-
1
tz.transition 1996, 3, :o5, 828234000
-
1
tz.transition 1996, 10, :o3, 846378000
-
1
tz.transition 1997, 3, :o5, 859683600
-
1
tz.transition 1997, 10, :o3, 877827600
-
1
tz.transition 1998, 3, :o5, 891133200
-
1
tz.transition 1998, 10, :o3, 909277200
-
1
tz.transition 1999, 3, :o5, 922582800
-
1
tz.transition 1999, 10, :o3, 941331600
-
1
tz.transition 2000, 3, :o5, 954032400
-
1
tz.transition 2000, 10, :o3, 972781200
-
1
tz.transition 2001, 3, :o5, 985482000
-
1
tz.transition 2001, 10, :o3, 1004230800
-
1
tz.transition 2002, 3, :o5, 1017536400
-
1
tz.transition 2002, 10, :o3, 1035680400
-
1
tz.transition 2003, 3, :o5, 1048986000
-
1
tz.transition 2003, 10, :o3, 1067130000
-
1
tz.transition 2004, 3, :o5, 1080435600
-
1
tz.transition 2004, 10, :o3, 1099184400
-
1
tz.transition 2005, 3, :o5, 1111885200
-
1
tz.transition 2005, 10, :o3, 1130634000
-
1
tz.transition 2006, 3, :o5, 1143334800
-
1
tz.transition 2006, 10, :o3, 1162083600
-
1
tz.transition 2007, 3, :o5, 1174784400
-
1
tz.transition 2007, 10, :o3, 1193533200
-
1
tz.transition 2008, 3, :o5, 1206838800
-
1
tz.transition 2008, 10, :o3, 1224982800
-
1
tz.transition 2009, 3, :o5, 1238288400
-
1
tz.transition 2009, 10, :o3, 1256432400
-
1
tz.transition 2010, 3, :o5, 1269738000
-
1
tz.transition 2010, 10, :o3, 1288486800
-
1
tz.transition 2011, 3, :o5, 1301187600
-
1
tz.transition 2011, 10, :o3, 1319936400
-
1
tz.transition 2012, 3, :o5, 1332637200
-
1
tz.transition 2012, 10, :o3, 1351386000
-
1
tz.transition 2013, 3, :o5, 1364691600
-
1
tz.transition 2013, 10, :o3, 1382835600
-
1
tz.transition 2014, 3, :o5, 1396141200
-
1
tz.transition 2014, 10, :o3, 1414285200
-
1
tz.transition 2015, 3, :o5, 1427590800
-
1
tz.transition 2015, 10, :o3, 1445734800
-
1
tz.transition 2016, 3, :o5, 1459040400
-
1
tz.transition 2016, 10, :o3, 1477789200
-
1
tz.transition 2017, 3, :o5, 1490490000
-
1
tz.transition 2017, 10, :o3, 1509238800
-
1
tz.transition 2018, 3, :o5, 1521939600
-
1
tz.transition 2018, 10, :o3, 1540688400
-
1
tz.transition 2019, 3, :o5, 1553994000
-
1
tz.transition 2019, 10, :o3, 1572138000
-
1
tz.transition 2020, 3, :o5, 1585443600
-
1
tz.transition 2020, 10, :o3, 1603587600
-
1
tz.transition 2021, 3, :o5, 1616893200
-
1
tz.transition 2021, 10, :o3, 1635642000
-
1
tz.transition 2022, 3, :o5, 1648342800
-
1
tz.transition 2022, 10, :o3, 1667091600
-
1
tz.transition 2023, 3, :o5, 1679792400
-
1
tz.transition 2023, 10, :o3, 1698541200
-
1
tz.transition 2024, 3, :o5, 1711846800
-
1
tz.transition 2024, 10, :o3, 1729990800
-
1
tz.transition 2025, 3, :o5, 1743296400
-
1
tz.transition 2025, 10, :o3, 1761440400
-
1
tz.transition 2026, 3, :o5, 1774746000
-
1
tz.transition 2026, 10, :o3, 1792890000
-
1
tz.transition 2027, 3, :o5, 1806195600
-
1
tz.transition 2027, 10, :o3, 1824944400
-
1
tz.transition 2028, 3, :o5, 1837645200
-
1
tz.transition 2028, 10, :o3, 1856394000
-
1
tz.transition 2029, 3, :o5, 1869094800
-
1
tz.transition 2029, 10, :o3, 1887843600
-
1
tz.transition 2030, 3, :o5, 1901149200
-
1
tz.transition 2030, 10, :o3, 1919293200
-
1
tz.transition 2031, 3, :o5, 1932598800
-
1
tz.transition 2031, 10, :o3, 1950742800
-
1
tz.transition 2032, 3, :o5, 1964048400
-
1
tz.transition 2032, 10, :o3, 1982797200
-
1
tz.transition 2033, 3, :o5, 1995498000
-
1
tz.transition 2033, 10, :o3, 2014246800
-
1
tz.transition 2034, 3, :o5, 2026947600
-
1
tz.transition 2034, 10, :o3, 2045696400
-
1
tz.transition 2035, 3, :o5, 2058397200
-
1
tz.transition 2035, 10, :o3, 2077146000
-
1
tz.transition 2036, 3, :o5, 2090451600
-
1
tz.transition 2036, 10, :o3, 2108595600
-
1
tz.transition 2037, 3, :o5, 2121901200
-
1
tz.transition 2037, 10, :o3, 2140045200
-
1
tz.transition 2038, 3, :o5, 59172253, 24
-
1
tz.transition 2038, 10, :o3, 59177461, 24
-
1
tz.transition 2039, 3, :o5, 59180989, 24
-
1
tz.transition 2039, 10, :o3, 59186197, 24
-
1
tz.transition 2040, 3, :o5, 59189725, 24
-
1
tz.transition 2040, 10, :o3, 59194933, 24
-
1
tz.transition 2041, 3, :o5, 59198629, 24
-
1
tz.transition 2041, 10, :o3, 59203669, 24
-
1
tz.transition 2042, 3, :o5, 59207365, 24
-
1
tz.transition 2042, 10, :o3, 59212405, 24
-
1
tz.transition 2043, 3, :o5, 59216101, 24
-
1
tz.transition 2043, 10, :o3, 59221141, 24
-
1
tz.transition 2044, 3, :o5, 59224837, 24
-
1
tz.transition 2044, 10, :o3, 59230045, 24
-
1
tz.transition 2045, 3, :o5, 59233573, 24
-
1
tz.transition 2045, 10, :o3, 59238781, 24
-
1
tz.transition 2046, 3, :o5, 59242309, 24
-
1
tz.transition 2046, 10, :o3, 59247517, 24
-
1
tz.transition 2047, 3, :o5, 59251213, 24
-
1
tz.transition 2047, 10, :o3, 59256253, 24
-
1
tz.transition 2048, 3, :o5, 59259949, 24
-
1
tz.transition 2048, 10, :o3, 59264989, 24
-
1
tz.transition 2049, 3, :o5, 59268685, 24
-
1
tz.transition 2049, 10, :o3, 59273893, 24
-
1
tz.transition 2050, 3, :o5, 59277421, 24
-
1
tz.transition 2050, 10, :o3, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Helsinki
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Helsinki' do |tz|
-
1
tz.offset :o0, 5992, 0, :LMT
-
1
tz.offset :o1, 5992, 0, :HMT
-
1
tz.offset :o2, 7200, 0, :EET
-
1
tz.offset :o3, 7200, 3600, :EEST
-
-
1
tz.transition 1878, 5, :o1, 25997062651, 10800
-
1
tz.transition 1921, 4, :o2, 26166352651, 10800
-
1
tz.transition 1942, 4, :o3, 29165429, 12
-
1
tz.transition 1942, 10, :o2, 19445083, 8
-
1
tz.transition 1981, 3, :o3, 354672000
-
1
tz.transition 1981, 9, :o2, 370396800
-
1
tz.transition 1982, 3, :o3, 386121600
-
1
tz.transition 1982, 9, :o2, 401846400
-
1
tz.transition 1983, 3, :o3, 417574800
-
1
tz.transition 1983, 9, :o2, 433299600
-
1
tz.transition 1984, 3, :o3, 449024400
-
1
tz.transition 1984, 9, :o2, 465354000
-
1
tz.transition 1985, 3, :o3, 481078800
-
1
tz.transition 1985, 9, :o2, 496803600
-
1
tz.transition 1986, 3, :o3, 512528400
-
1
tz.transition 1986, 9, :o2, 528253200
-
1
tz.transition 1987, 3, :o3, 543978000
-
1
tz.transition 1987, 9, :o2, 559702800
-
1
tz.transition 1988, 3, :o3, 575427600
-
1
tz.transition 1988, 9, :o2, 591152400
-
1
tz.transition 1989, 3, :o3, 606877200
-
1
tz.transition 1989, 9, :o2, 622602000
-
1
tz.transition 1990, 3, :o3, 638326800
-
1
tz.transition 1990, 9, :o2, 654656400
-
1
tz.transition 1991, 3, :o3, 670381200
-
1
tz.transition 1991, 9, :o2, 686106000
-
1
tz.transition 1992, 3, :o3, 701830800
-
1
tz.transition 1992, 9, :o2, 717555600
-
1
tz.transition 1993, 3, :o3, 733280400
-
1
tz.transition 1993, 9, :o2, 749005200
-
1
tz.transition 1994, 3, :o3, 764730000
-
1
tz.transition 1994, 9, :o2, 780454800
-
1
tz.transition 1995, 3, :o3, 796179600
-
1
tz.transition 1995, 9, :o2, 811904400
-
1
tz.transition 1996, 3, :o3, 828234000
-
1
tz.transition 1996, 10, :o2, 846378000
-
1
tz.transition 1997, 3, :o3, 859683600
-
1
tz.transition 1997, 10, :o2, 877827600
-
1
tz.transition 1998, 3, :o3, 891133200
-
1
tz.transition 1998, 10, :o2, 909277200
-
1
tz.transition 1999, 3, :o3, 922582800
-
1
tz.transition 1999, 10, :o2, 941331600
-
1
tz.transition 2000, 3, :o3, 954032400
-
1
tz.transition 2000, 10, :o2, 972781200
-
1
tz.transition 2001, 3, :o3, 985482000
-
1
tz.transition 2001, 10, :o2, 1004230800
-
1
tz.transition 2002, 3, :o3, 1017536400
-
1
tz.transition 2002, 10, :o2, 1035680400
-
1
tz.transition 2003, 3, :o3, 1048986000
-
1
tz.transition 2003, 10, :o2, 1067130000
-
1
tz.transition 2004, 3, :o3, 1080435600
-
1
tz.transition 2004, 10, :o2, 1099184400
-
1
tz.transition 2005, 3, :o3, 1111885200
-
1
tz.transition 2005, 10, :o2, 1130634000
-
1
tz.transition 2006, 3, :o3, 1143334800
-
1
tz.transition 2006, 10, :o2, 1162083600
-
1
tz.transition 2007, 3, :o3, 1174784400
-
1
tz.transition 2007, 10, :o2, 1193533200
-
1
tz.transition 2008, 3, :o3, 1206838800
-
1
tz.transition 2008, 10, :o2, 1224982800
-
1
tz.transition 2009, 3, :o3, 1238288400
-
1
tz.transition 2009, 10, :o2, 1256432400
-
1
tz.transition 2010, 3, :o3, 1269738000
-
1
tz.transition 2010, 10, :o2, 1288486800
-
1
tz.transition 2011, 3, :o3, 1301187600
-
1
tz.transition 2011, 10, :o2, 1319936400
-
1
tz.transition 2012, 3, :o3, 1332637200
-
1
tz.transition 2012, 10, :o2, 1351386000
-
1
tz.transition 2013, 3, :o3, 1364691600
-
1
tz.transition 2013, 10, :o2, 1382835600
-
1
tz.transition 2014, 3, :o3, 1396141200
-
1
tz.transition 2014, 10, :o2, 1414285200
-
1
tz.transition 2015, 3, :o3, 1427590800
-
1
tz.transition 2015, 10, :o2, 1445734800
-
1
tz.transition 2016, 3, :o3, 1459040400
-
1
tz.transition 2016, 10, :o2, 1477789200
-
1
tz.transition 2017, 3, :o3, 1490490000
-
1
tz.transition 2017, 10, :o2, 1509238800
-
1
tz.transition 2018, 3, :o3, 1521939600
-
1
tz.transition 2018, 10, :o2, 1540688400
-
1
tz.transition 2019, 3, :o3, 1553994000
-
1
tz.transition 2019, 10, :o2, 1572138000
-
1
tz.transition 2020, 3, :o3, 1585443600
-
1
tz.transition 2020, 10, :o2, 1603587600
-
1
tz.transition 2021, 3, :o3, 1616893200
-
1
tz.transition 2021, 10, :o2, 1635642000
-
1
tz.transition 2022, 3, :o3, 1648342800
-
1
tz.transition 2022, 10, :o2, 1667091600
-
1
tz.transition 2023, 3, :o3, 1679792400
-
1
tz.transition 2023, 10, :o2, 1698541200
-
1
tz.transition 2024, 3, :o3, 1711846800
-
1
tz.transition 2024, 10, :o2, 1729990800
-
1
tz.transition 2025, 3, :o3, 1743296400
-
1
tz.transition 2025, 10, :o2, 1761440400
-
1
tz.transition 2026, 3, :o3, 1774746000
-
1
tz.transition 2026, 10, :o2, 1792890000
-
1
tz.transition 2027, 3, :o3, 1806195600
-
1
tz.transition 2027, 10, :o2, 1824944400
-
1
tz.transition 2028, 3, :o3, 1837645200
-
1
tz.transition 2028, 10, :o2, 1856394000
-
1
tz.transition 2029, 3, :o3, 1869094800
-
1
tz.transition 2029, 10, :o2, 1887843600
-
1
tz.transition 2030, 3, :o3, 1901149200
-
1
tz.transition 2030, 10, :o2, 1919293200
-
1
tz.transition 2031, 3, :o3, 1932598800
-
1
tz.transition 2031, 10, :o2, 1950742800
-
1
tz.transition 2032, 3, :o3, 1964048400
-
1
tz.transition 2032, 10, :o2, 1982797200
-
1
tz.transition 2033, 3, :o3, 1995498000
-
1
tz.transition 2033, 10, :o2, 2014246800
-
1
tz.transition 2034, 3, :o3, 2026947600
-
1
tz.transition 2034, 10, :o2, 2045696400
-
1
tz.transition 2035, 3, :o3, 2058397200
-
1
tz.transition 2035, 10, :o2, 2077146000
-
1
tz.transition 2036, 3, :o3, 2090451600
-
1
tz.transition 2036, 10, :o2, 2108595600
-
1
tz.transition 2037, 3, :o3, 2121901200
-
1
tz.transition 2037, 10, :o2, 2140045200
-
1
tz.transition 2038, 3, :o3, 59172253, 24
-
1
tz.transition 2038, 10, :o2, 59177461, 24
-
1
tz.transition 2039, 3, :o3, 59180989, 24
-
1
tz.transition 2039, 10, :o2, 59186197, 24
-
1
tz.transition 2040, 3, :o3, 59189725, 24
-
1
tz.transition 2040, 10, :o2, 59194933, 24
-
1
tz.transition 2041, 3, :o3, 59198629, 24
-
1
tz.transition 2041, 10, :o2, 59203669, 24
-
1
tz.transition 2042, 3, :o3, 59207365, 24
-
1
tz.transition 2042, 10, :o2, 59212405, 24
-
1
tz.transition 2043, 3, :o3, 59216101, 24
-
1
tz.transition 2043, 10, :o2, 59221141, 24
-
1
tz.transition 2044, 3, :o3, 59224837, 24
-
1
tz.transition 2044, 10, :o2, 59230045, 24
-
1
tz.transition 2045, 3, :o3, 59233573, 24
-
1
tz.transition 2045, 10, :o2, 59238781, 24
-
1
tz.transition 2046, 3, :o3, 59242309, 24
-
1
tz.transition 2046, 10, :o2, 59247517, 24
-
1
tz.transition 2047, 3, :o3, 59251213, 24
-
1
tz.transition 2047, 10, :o2, 59256253, 24
-
1
tz.transition 2048, 3, :o3, 59259949, 24
-
1
tz.transition 2048, 10, :o2, 59264989, 24
-
1
tz.transition 2049, 3, :o3, 59268685, 24
-
1
tz.transition 2049, 10, :o2, 59273893, 24
-
1
tz.transition 2050, 3, :o3, 59277421, 24
-
1
tz.transition 2050, 10, :o2, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Istanbul
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Istanbul' do |tz|
-
1
tz.offset :o0, 6952, 0, :LMT
-
1
tz.offset :o1, 7016, 0, :IMT
-
1
tz.offset :o2, 7200, 0, :EET
-
1
tz.offset :o3, 7200, 3600, :EEST
-
1
tz.offset :o4, 10800, 3600, :TRST
-
1
tz.offset :o5, 10800, 0, :TRT
-
-
1
tz.transition 1879, 12, :o1, 26003326531, 10800
-
1
tz.transition 1910, 9, :o2, 26124610523, 10800
-
1
tz.transition 1916, 4, :o3, 29051813, 12
-
1
tz.transition 1916, 9, :o2, 19369099, 8
-
1
tz.transition 1920, 3, :o3, 29068937, 12
-
1
tz.transition 1920, 10, :o2, 19380979, 8
-
1
tz.transition 1921, 4, :o3, 29073389, 12
-
1
tz.transition 1921, 10, :o2, 19383723, 8
-
1
tz.transition 1922, 3, :o3, 29077673, 12
-
1
tz.transition 1922, 10, :o2, 19386683, 8
-
1
tz.transition 1924, 5, :o3, 29087021, 12
-
1
tz.transition 1924, 9, :o2, 19392475, 8
-
1
tz.transition 1925, 4, :o3, 29091257, 12
-
1
tz.transition 1925, 9, :o2, 19395395, 8
-
1
tz.transition 1940, 6, :o3, 29157725, 12
-
1
tz.transition 1940, 10, :o2, 19439259, 8
-
1
tz.transition 1940, 11, :o3, 29159573, 12
-
1
tz.transition 1941, 9, :o2, 19442067, 8
-
1
tz.transition 1942, 3, :o3, 29165405, 12
-
1
tz.transition 1942, 10, :o2, 19445315, 8
-
1
tz.transition 1945, 4, :o3, 29178569, 12
-
1
tz.transition 1945, 10, :o2, 19453891, 8
-
1
tz.transition 1946, 5, :o3, 29183669, 12
-
1
tz.transition 1946, 9, :o2, 19456755, 8
-
1
tz.transition 1947, 4, :o3, 29187545, 12
-
1
tz.transition 1947, 10, :o2, 19459707, 8
-
1
tz.transition 1948, 4, :o3, 29191913, 12
-
1
tz.transition 1948, 10, :o2, 19462619, 8
-
1
tz.transition 1949, 4, :o3, 29196197, 12
-
1
tz.transition 1949, 10, :o2, 19465531, 8
-
1
tz.transition 1950, 4, :o3, 29200685, 12
-
1
tz.transition 1950, 10, :o2, 19468499, 8
-
1
tz.transition 1951, 4, :o3, 29205101, 12
-
1
tz.transition 1951, 10, :o2, 19471419, 8
-
1
tz.transition 1962, 7, :o3, 29254325, 12
-
1
tz.transition 1962, 10, :o2, 19503563, 8
-
1
tz.transition 1964, 5, :o3, 29262365, 12
-
1
tz.transition 1964, 9, :o2, 19509355, 8
-
1
tz.transition 1970, 5, :o3, 10533600
-
1
tz.transition 1970, 10, :o2, 23835600
-
1
tz.transition 1971, 5, :o3, 41983200
-
1
tz.transition 1971, 10, :o2, 55285200
-
1
tz.transition 1972, 5, :o3, 74037600
-
1
tz.transition 1972, 10, :o2, 87339600
-
1
tz.transition 1973, 6, :o3, 107910000
-
1
tz.transition 1973, 11, :o2, 121219200
-
1
tz.transition 1974, 3, :o3, 133920000
-
1
tz.transition 1974, 11, :o2, 152676000
-
1
tz.transition 1975, 3, :o3, 165362400
-
1
tz.transition 1975, 10, :o2, 183502800
-
1
tz.transition 1976, 5, :o3, 202428000
-
1
tz.transition 1976, 10, :o2, 215557200
-
1
tz.transition 1977, 4, :o3, 228866400
-
1
tz.transition 1977, 10, :o2, 245797200
-
1
tz.transition 1978, 4, :o3, 260316000
-
1
tz.transition 1978, 10, :o4, 277246800
-
1
tz.transition 1979, 10, :o5, 308779200
-
1
tz.transition 1980, 4, :o4, 323827200
-
1
tz.transition 1980, 10, :o5, 340228800
-
1
tz.transition 1981, 3, :o4, 354672000
-
1
tz.transition 1981, 10, :o5, 371678400
-
1
tz.transition 1982, 3, :o4, 386121600
-
1
tz.transition 1982, 10, :o5, 403128000
-
1
tz.transition 1983, 7, :o4, 428446800
-
1
tz.transition 1983, 10, :o5, 433886400
-
1
tz.transition 1985, 4, :o3, 482792400
-
1
tz.transition 1985, 9, :o2, 496702800
-
1
tz.transition 1986, 3, :o3, 512524800
-
1
tz.transition 1986, 9, :o2, 528249600
-
1
tz.transition 1987, 3, :o3, 543974400
-
1
tz.transition 1987, 9, :o2, 559699200
-
1
tz.transition 1988, 3, :o3, 575424000
-
1
tz.transition 1988, 9, :o2, 591148800
-
1
tz.transition 1989, 3, :o3, 606873600
-
1
tz.transition 1989, 9, :o2, 622598400
-
1
tz.transition 1990, 3, :o3, 638323200
-
1
tz.transition 1990, 9, :o2, 654652800
-
1
tz.transition 1991, 3, :o3, 670374000
-
1
tz.transition 1991, 9, :o2, 686098800
-
1
tz.transition 1992, 3, :o3, 701823600
-
1
tz.transition 1992, 9, :o2, 717548400
-
1
tz.transition 1993, 3, :o3, 733273200
-
1
tz.transition 1993, 9, :o2, 748998000
-
1
tz.transition 1994, 3, :o3, 764722800
-
1
tz.transition 1994, 9, :o2, 780447600
-
1
tz.transition 1995, 3, :o3, 796172400
-
1
tz.transition 1995, 9, :o2, 811897200
-
1
tz.transition 1996, 3, :o3, 828226800
-
1
tz.transition 1996, 10, :o2, 846370800
-
1
tz.transition 1997, 3, :o3, 859676400
-
1
tz.transition 1997, 10, :o2, 877820400
-
1
tz.transition 1998, 3, :o3, 891126000
-
1
tz.transition 1998, 10, :o2, 909270000
-
1
tz.transition 1999, 3, :o3, 922575600
-
1
tz.transition 1999, 10, :o2, 941324400
-
1
tz.transition 2000, 3, :o3, 954025200
-
1
tz.transition 2000, 10, :o2, 972774000
-
1
tz.transition 2001, 3, :o3, 985474800
-
1
tz.transition 2001, 10, :o2, 1004223600
-
1
tz.transition 2002, 3, :o3, 1017529200
-
1
tz.transition 2002, 10, :o2, 1035673200
-
1
tz.transition 2003, 3, :o3, 1048978800
-
1
tz.transition 2003, 10, :o2, 1067122800
-
1
tz.transition 2004, 3, :o3, 1080428400
-
1
tz.transition 2004, 10, :o2, 1099177200
-
1
tz.transition 2005, 3, :o3, 1111878000
-
1
tz.transition 2005, 10, :o2, 1130626800
-
1
tz.transition 2006, 3, :o3, 1143327600
-
1
tz.transition 2006, 10, :o2, 1162076400
-
1
tz.transition 2007, 3, :o3, 1174784400
-
1
tz.transition 2007, 10, :o2, 1193533200
-
1
tz.transition 2008, 3, :o3, 1206838800
-
1
tz.transition 2008, 10, :o2, 1224982800
-
1
tz.transition 2009, 3, :o3, 1238288400
-
1
tz.transition 2009, 10, :o2, 1256432400
-
1
tz.transition 2010, 3, :o3, 1269738000
-
1
tz.transition 2010, 10, :o2, 1288486800
-
1
tz.transition 2011, 3, :o3, 1301274000
-
1
tz.transition 2011, 10, :o2, 1319936400
-
1
tz.transition 2012, 3, :o3, 1332637200
-
1
tz.transition 2012, 10, :o2, 1351386000
-
1
tz.transition 2013, 3, :o3, 1364691600
-
1
tz.transition 2013, 10, :o2, 1382835600
-
1
tz.transition 2014, 3, :o3, 1396141200
-
1
tz.transition 2014, 10, :o2, 1414285200
-
1
tz.transition 2015, 3, :o3, 1427590800
-
1
tz.transition 2015, 10, :o2, 1445734800
-
1
tz.transition 2016, 3, :o3, 1459040400
-
1
tz.transition 2016, 10, :o2, 1477789200
-
1
tz.transition 2017, 3, :o3, 1490490000
-
1
tz.transition 2017, 10, :o2, 1509238800
-
1
tz.transition 2018, 3, :o3, 1521939600
-
1
tz.transition 2018, 10, :o2, 1540688400
-
1
tz.transition 2019, 3, :o3, 1553994000
-
1
tz.transition 2019, 10, :o2, 1572138000
-
1
tz.transition 2020, 3, :o3, 1585443600
-
1
tz.transition 2020, 10, :o2, 1603587600
-
1
tz.transition 2021, 3, :o3, 1616893200
-
1
tz.transition 2021, 10, :o2, 1635642000
-
1
tz.transition 2022, 3, :o3, 1648342800
-
1
tz.transition 2022, 10, :o2, 1667091600
-
1
tz.transition 2023, 3, :o3, 1679792400
-
1
tz.transition 2023, 10, :o2, 1698541200
-
1
tz.transition 2024, 3, :o3, 1711846800
-
1
tz.transition 2024, 10, :o2, 1729990800
-
1
tz.transition 2025, 3, :o3, 1743296400
-
1
tz.transition 2025, 10, :o2, 1761440400
-
1
tz.transition 2026, 3, :o3, 1774746000
-
1
tz.transition 2026, 10, :o2, 1792890000
-
1
tz.transition 2027, 3, :o3, 1806195600
-
1
tz.transition 2027, 10, :o2, 1824944400
-
1
tz.transition 2028, 3, :o3, 1837645200
-
1
tz.transition 2028, 10, :o2, 1856394000
-
1
tz.transition 2029, 3, :o3, 1869094800
-
1
tz.transition 2029, 10, :o2, 1887843600
-
1
tz.transition 2030, 3, :o3, 1901149200
-
1
tz.transition 2030, 10, :o2, 1919293200
-
1
tz.transition 2031, 3, :o3, 1932598800
-
1
tz.transition 2031, 10, :o2, 1950742800
-
1
tz.transition 2032, 3, :o3, 1964048400
-
1
tz.transition 2032, 10, :o2, 1982797200
-
1
tz.transition 2033, 3, :o3, 1995498000
-
1
tz.transition 2033, 10, :o2, 2014246800
-
1
tz.transition 2034, 3, :o3, 2026947600
-
1
tz.transition 2034, 10, :o2, 2045696400
-
1
tz.transition 2035, 3, :o3, 2058397200
-
1
tz.transition 2035, 10, :o2, 2077146000
-
1
tz.transition 2036, 3, :o3, 2090451600
-
1
tz.transition 2036, 10, :o2, 2108595600
-
1
tz.transition 2037, 3, :o3, 2121901200
-
1
tz.transition 2037, 10, :o2, 2140045200
-
1
tz.transition 2038, 3, :o3, 59172253, 24
-
1
tz.transition 2038, 10, :o2, 59177461, 24
-
1
tz.transition 2039, 3, :o3, 59180989, 24
-
1
tz.transition 2039, 10, :o2, 59186197, 24
-
1
tz.transition 2040, 3, :o3, 59189725, 24
-
1
tz.transition 2040, 10, :o2, 59194933, 24
-
1
tz.transition 2041, 3, :o3, 59198629, 24
-
1
tz.transition 2041, 10, :o2, 59203669, 24
-
1
tz.transition 2042, 3, :o3, 59207365, 24
-
1
tz.transition 2042, 10, :o2, 59212405, 24
-
1
tz.transition 2043, 3, :o3, 59216101, 24
-
1
tz.transition 2043, 10, :o2, 59221141, 24
-
1
tz.transition 2044, 3, :o3, 59224837, 24
-
1
tz.transition 2044, 10, :o2, 59230045, 24
-
1
tz.transition 2045, 3, :o3, 59233573, 24
-
1
tz.transition 2045, 10, :o2, 59238781, 24
-
1
tz.transition 2046, 3, :o3, 59242309, 24
-
1
tz.transition 2046, 10, :o2, 59247517, 24
-
1
tz.transition 2047, 3, :o3, 59251213, 24
-
1
tz.transition 2047, 10, :o2, 59256253, 24
-
1
tz.transition 2048, 3, :o3, 59259949, 24
-
1
tz.transition 2048, 10, :o2, 59264989, 24
-
1
tz.transition 2049, 3, :o3, 59268685, 24
-
1
tz.transition 2049, 10, :o2, 59273893, 24
-
1
tz.transition 2050, 3, :o3, 59277421, 24
-
1
tz.transition 2050, 10, :o2, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Kiev
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Kiev' do |tz|
-
1
tz.offset :o0, 7324, 0, :LMT
-
1
tz.offset :o1, 7324, 0, :KMT
-
1
tz.offset :o2, 7200, 0, :EET
-
1
tz.offset :o3, 10800, 0, :MSK
-
1
tz.offset :o4, 3600, 3600, :CEST
-
1
tz.offset :o5, 3600, 0, :CET
-
1
tz.offset :o6, 10800, 3600, :MSD
-
1
tz.offset :o7, 7200, 3600, :EEST
-
-
1
tz.transition 1879, 12, :o1, 52006652969, 21600
-
1
tz.transition 1924, 5, :o2, 52356400169, 21600
-
1
tz.transition 1930, 6, :o3, 29113781, 12
-
1
tz.transition 1941, 9, :o4, 19442059, 8
-
1
tz.transition 1942, 11, :o5, 58335973, 24
-
1
tz.transition 1943, 3, :o4, 58339501, 24
-
1
tz.transition 1943, 10, :o5, 58344037, 24
-
1
tz.transition 1943, 11, :o3, 58344827, 24
-
1
tz.transition 1981, 3, :o6, 354920400
-
1
tz.transition 1981, 9, :o3, 370728000
-
1
tz.transition 1982, 3, :o6, 386456400
-
1
tz.transition 1982, 9, :o3, 402264000
-
1
tz.transition 1983, 3, :o6, 417992400
-
1
tz.transition 1983, 9, :o3, 433800000
-
1
tz.transition 1984, 3, :o6, 449614800
-
1
tz.transition 1984, 9, :o3, 465346800
-
1
tz.transition 1985, 3, :o6, 481071600
-
1
tz.transition 1985, 9, :o3, 496796400
-
1
tz.transition 1986, 3, :o6, 512521200
-
1
tz.transition 1986, 9, :o3, 528246000
-
1
tz.transition 1987, 3, :o6, 543970800
-
1
tz.transition 1987, 9, :o3, 559695600
-
1
tz.transition 1988, 3, :o6, 575420400
-
1
tz.transition 1988, 9, :o3, 591145200
-
1
tz.transition 1989, 3, :o6, 606870000
-
1
tz.transition 1989, 9, :o3, 622594800
-
1
tz.transition 1990, 6, :o2, 646786800
-
1
tz.transition 1992, 3, :o7, 701820000
-
1
tz.transition 1992, 9, :o2, 717541200
-
1
tz.transition 1993, 3, :o7, 733269600
-
1
tz.transition 1993, 9, :o2, 748990800
-
1
tz.transition 1994, 3, :o7, 764719200
-
1
tz.transition 1994, 9, :o2, 780440400
-
1
tz.transition 1995, 3, :o7, 796179600
-
1
tz.transition 1995, 9, :o2, 811904400
-
1
tz.transition 1996, 3, :o7, 828234000
-
1
tz.transition 1996, 10, :o2, 846378000
-
1
tz.transition 1997, 3, :o7, 859683600
-
1
tz.transition 1997, 10, :o2, 877827600
-
1
tz.transition 1998, 3, :o7, 891133200
-
1
tz.transition 1998, 10, :o2, 909277200
-
1
tz.transition 1999, 3, :o7, 922582800
-
1
tz.transition 1999, 10, :o2, 941331600
-
1
tz.transition 2000, 3, :o7, 954032400
-
1
tz.transition 2000, 10, :o2, 972781200
-
1
tz.transition 2001, 3, :o7, 985482000
-
1
tz.transition 2001, 10, :o2, 1004230800
-
1
tz.transition 2002, 3, :o7, 1017536400
-
1
tz.transition 2002, 10, :o2, 1035680400
-
1
tz.transition 2003, 3, :o7, 1048986000
-
1
tz.transition 2003, 10, :o2, 1067130000
-
1
tz.transition 2004, 3, :o7, 1080435600
-
1
tz.transition 2004, 10, :o2, 1099184400
-
1
tz.transition 2005, 3, :o7, 1111885200
-
1
tz.transition 2005, 10, :o2, 1130634000
-
1
tz.transition 2006, 3, :o7, 1143334800
-
1
tz.transition 2006, 10, :o2, 1162083600
-
1
tz.transition 2007, 3, :o7, 1174784400
-
1
tz.transition 2007, 10, :o2, 1193533200
-
1
tz.transition 2008, 3, :o7, 1206838800
-
1
tz.transition 2008, 10, :o2, 1224982800
-
1
tz.transition 2009, 3, :o7, 1238288400
-
1
tz.transition 2009, 10, :o2, 1256432400
-
1
tz.transition 2010, 3, :o7, 1269738000
-
1
tz.transition 2010, 10, :o2, 1288486800
-
1
tz.transition 2011, 3, :o7, 1301187600
-
1
tz.transition 2011, 10, :o2, 1319936400
-
1
tz.transition 2012, 3, :o7, 1332637200
-
1
tz.transition 2012, 10, :o2, 1351386000
-
1
tz.transition 2013, 3, :o7, 1364691600
-
1
tz.transition 2013, 10, :o2, 1382835600
-
1
tz.transition 2014, 3, :o7, 1396141200
-
1
tz.transition 2014, 10, :o2, 1414285200
-
1
tz.transition 2015, 3, :o7, 1427590800
-
1
tz.transition 2015, 10, :o2, 1445734800
-
1
tz.transition 2016, 3, :o7, 1459040400
-
1
tz.transition 2016, 10, :o2, 1477789200
-
1
tz.transition 2017, 3, :o7, 1490490000
-
1
tz.transition 2017, 10, :o2, 1509238800
-
1
tz.transition 2018, 3, :o7, 1521939600
-
1
tz.transition 2018, 10, :o2, 1540688400
-
1
tz.transition 2019, 3, :o7, 1553994000
-
1
tz.transition 2019, 10, :o2, 1572138000
-
1
tz.transition 2020, 3, :o7, 1585443600
-
1
tz.transition 2020, 10, :o2, 1603587600
-
1
tz.transition 2021, 3, :o7, 1616893200
-
1
tz.transition 2021, 10, :o2, 1635642000
-
1
tz.transition 2022, 3, :o7, 1648342800
-
1
tz.transition 2022, 10, :o2, 1667091600
-
1
tz.transition 2023, 3, :o7, 1679792400
-
1
tz.transition 2023, 10, :o2, 1698541200
-
1
tz.transition 2024, 3, :o7, 1711846800
-
1
tz.transition 2024, 10, :o2, 1729990800
-
1
tz.transition 2025, 3, :o7, 1743296400
-
1
tz.transition 2025, 10, :o2, 1761440400
-
1
tz.transition 2026, 3, :o7, 1774746000
-
1
tz.transition 2026, 10, :o2, 1792890000
-
1
tz.transition 2027, 3, :o7, 1806195600
-
1
tz.transition 2027, 10, :o2, 1824944400
-
1
tz.transition 2028, 3, :o7, 1837645200
-
1
tz.transition 2028, 10, :o2, 1856394000
-
1
tz.transition 2029, 3, :o7, 1869094800
-
1
tz.transition 2029, 10, :o2, 1887843600
-
1
tz.transition 2030, 3, :o7, 1901149200
-
1
tz.transition 2030, 10, :o2, 1919293200
-
1
tz.transition 2031, 3, :o7, 1932598800
-
1
tz.transition 2031, 10, :o2, 1950742800
-
1
tz.transition 2032, 3, :o7, 1964048400
-
1
tz.transition 2032, 10, :o2, 1982797200
-
1
tz.transition 2033, 3, :o7, 1995498000
-
1
tz.transition 2033, 10, :o2, 2014246800
-
1
tz.transition 2034, 3, :o7, 2026947600
-
1
tz.transition 2034, 10, :o2, 2045696400
-
1
tz.transition 2035, 3, :o7, 2058397200
-
1
tz.transition 2035, 10, :o2, 2077146000
-
1
tz.transition 2036, 3, :o7, 2090451600
-
1
tz.transition 2036, 10, :o2, 2108595600
-
1
tz.transition 2037, 3, :o7, 2121901200
-
1
tz.transition 2037, 10, :o2, 2140045200
-
1
tz.transition 2038, 3, :o7, 59172253, 24
-
1
tz.transition 2038, 10, :o2, 59177461, 24
-
1
tz.transition 2039, 3, :o7, 59180989, 24
-
1
tz.transition 2039, 10, :o2, 59186197, 24
-
1
tz.transition 2040, 3, :o7, 59189725, 24
-
1
tz.transition 2040, 10, :o2, 59194933, 24
-
1
tz.transition 2041, 3, :o7, 59198629, 24
-
1
tz.transition 2041, 10, :o2, 59203669, 24
-
1
tz.transition 2042, 3, :o7, 59207365, 24
-
1
tz.transition 2042, 10, :o2, 59212405, 24
-
1
tz.transition 2043, 3, :o7, 59216101, 24
-
1
tz.transition 2043, 10, :o2, 59221141, 24
-
1
tz.transition 2044, 3, :o7, 59224837, 24
-
1
tz.transition 2044, 10, :o2, 59230045, 24
-
1
tz.transition 2045, 3, :o7, 59233573, 24
-
1
tz.transition 2045, 10, :o2, 59238781, 24
-
1
tz.transition 2046, 3, :o7, 59242309, 24
-
1
tz.transition 2046, 10, :o2, 59247517, 24
-
1
tz.transition 2047, 3, :o7, 59251213, 24
-
1
tz.transition 2047, 10, :o2, 59256253, 24
-
1
tz.transition 2048, 3, :o7, 59259949, 24
-
1
tz.transition 2048, 10, :o2, 59264989, 24
-
1
tz.transition 2049, 3, :o7, 59268685, 24
-
1
tz.transition 2049, 10, :o2, 59273893, 24
-
1
tz.transition 2050, 3, :o7, 59277421, 24
-
1
tz.transition 2050, 10, :o2, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Lisbon
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Lisbon' do |tz|
-
1
tz.offset :o0, -2192, 0, :LMT
-
1
tz.offset :o1, 0, 0, :WET
-
1
tz.offset :o2, 0, 3600, :WEST
-
1
tz.offset :o3, 0, 7200, :WEMT
-
1
tz.offset :o4, 3600, 0, :CET
-
1
tz.offset :o5, 3600, 3600, :CEST
-
-
1
tz.transition 1912, 1, :o1, 13064773637, 5400
-
1
tz.transition 1916, 6, :o2, 58104779, 24
-
1
tz.transition 1916, 11, :o1, 4842337, 2
-
1
tz.transition 1917, 2, :o2, 58110923, 24
-
1
tz.transition 1917, 10, :o1, 58116395, 24
-
1
tz.transition 1918, 3, :o2, 58119707, 24
-
1
tz.transition 1918, 10, :o1, 58125155, 24
-
1
tz.transition 1919, 2, :o2, 58128443, 24
-
1
tz.transition 1919, 10, :o1, 58133915, 24
-
1
tz.transition 1920, 2, :o2, 58137227, 24
-
1
tz.transition 1920, 10, :o1, 58142699, 24
-
1
tz.transition 1921, 2, :o2, 58145987, 24
-
1
tz.transition 1921, 10, :o1, 58151459, 24
-
1
tz.transition 1924, 4, :o2, 58173419, 24
-
1
tz.transition 1924, 10, :o1, 58177763, 24
-
1
tz.transition 1926, 4, :o2, 58190963, 24
-
1
tz.transition 1926, 10, :o1, 58194995, 24
-
1
tz.transition 1927, 4, :o2, 58199531, 24
-
1
tz.transition 1927, 10, :o1, 58203731, 24
-
1
tz.transition 1928, 4, :o2, 58208435, 24
-
1
tz.transition 1928, 10, :o1, 58212635, 24
-
1
tz.transition 1929, 4, :o2, 58217339, 24
-
1
tz.transition 1929, 10, :o1, 58221371, 24
-
1
tz.transition 1931, 4, :o2, 58234811, 24
-
1
tz.transition 1931, 10, :o1, 58238843, 24
-
1
tz.transition 1932, 4, :o2, 58243211, 24
-
1
tz.transition 1932, 10, :o1, 58247579, 24
-
1
tz.transition 1934, 4, :o2, 58260851, 24
-
1
tz.transition 1934, 10, :o1, 58265219, 24
-
1
tz.transition 1935, 3, :o2, 58269419, 24
-
1
tz.transition 1935, 10, :o1, 58273955, 24
-
1
tz.transition 1936, 4, :o2, 58278659, 24
-
1
tz.transition 1936, 10, :o1, 58282691, 24
-
1
tz.transition 1937, 4, :o2, 58287059, 24
-
1
tz.transition 1937, 10, :o1, 58291427, 24
-
1
tz.transition 1938, 3, :o2, 58295627, 24
-
1
tz.transition 1938, 10, :o1, 58300163, 24
-
1
tz.transition 1939, 4, :o2, 58304867, 24
-
1
tz.transition 1939, 11, :o1, 58310075, 24
-
1
tz.transition 1940, 2, :o2, 58312427, 24
-
1
tz.transition 1940, 10, :o1, 58317803, 24
-
1
tz.transition 1941, 4, :o2, 58322171, 24
-
1
tz.transition 1941, 10, :o1, 58326563, 24
-
1
tz.transition 1942, 3, :o2, 58330403, 24
-
1
tz.transition 1942, 4, :o3, 29165705, 12
-
1
tz.transition 1942, 8, :o2, 29167049, 12
-
1
tz.transition 1942, 10, :o1, 58335779, 24
-
1
tz.transition 1943, 3, :o2, 58339139, 24
-
1
tz.transition 1943, 4, :o3, 29169989, 12
-
1
tz.transition 1943, 8, :o2, 29171585, 12
-
1
tz.transition 1943, 10, :o1, 58344683, 24
-
1
tz.transition 1944, 3, :o2, 58347875, 24
-
1
tz.transition 1944, 4, :o3, 29174441, 12
-
1
tz.transition 1944, 8, :o2, 29175953, 12
-
1
tz.transition 1944, 10, :o1, 58353419, 24
-
1
tz.transition 1945, 3, :o2, 58356611, 24
-
1
tz.transition 1945, 4, :o3, 29178809, 12
-
1
tz.transition 1945, 8, :o2, 29180321, 12
-
1
tz.transition 1945, 10, :o1, 58362155, 24
-
1
tz.transition 1946, 4, :o2, 58366019, 24
-
1
tz.transition 1946, 10, :o1, 58370387, 24
-
1
tz.transition 1947, 4, :o2, 29187379, 12
-
1
tz.transition 1947, 10, :o1, 29189563, 12
-
1
tz.transition 1948, 4, :o2, 29191747, 12
-
1
tz.transition 1948, 10, :o1, 29193931, 12
-
1
tz.transition 1949, 4, :o2, 29196115, 12
-
1
tz.transition 1949, 10, :o1, 29198299, 12
-
1
tz.transition 1951, 4, :o2, 29204851, 12
-
1
tz.transition 1951, 10, :o1, 29207119, 12
-
1
tz.transition 1952, 4, :o2, 29209303, 12
-
1
tz.transition 1952, 10, :o1, 29211487, 12
-
1
tz.transition 1953, 4, :o2, 29213671, 12
-
1
tz.transition 1953, 10, :o1, 29215855, 12
-
1
tz.transition 1954, 4, :o2, 29218039, 12
-
1
tz.transition 1954, 10, :o1, 29220223, 12
-
1
tz.transition 1955, 4, :o2, 29222407, 12
-
1
tz.transition 1955, 10, :o1, 29224591, 12
-
1
tz.transition 1956, 4, :o2, 29226775, 12
-
1
tz.transition 1956, 10, :o1, 29229043, 12
-
1
tz.transition 1957, 4, :o2, 29231227, 12
-
1
tz.transition 1957, 10, :o1, 29233411, 12
-
1
tz.transition 1958, 4, :o2, 29235595, 12
-
1
tz.transition 1958, 10, :o1, 29237779, 12
-
1
tz.transition 1959, 4, :o2, 29239963, 12
-
1
tz.transition 1959, 10, :o1, 29242147, 12
-
1
tz.transition 1960, 4, :o2, 29244331, 12
-
1
tz.transition 1960, 10, :o1, 29246515, 12
-
1
tz.transition 1961, 4, :o2, 29248699, 12
-
1
tz.transition 1961, 10, :o1, 29250883, 12
-
1
tz.transition 1962, 4, :o2, 29253067, 12
-
1
tz.transition 1962, 10, :o1, 29255335, 12
-
1
tz.transition 1963, 4, :o2, 29257519, 12
-
1
tz.transition 1963, 10, :o1, 29259703, 12
-
1
tz.transition 1964, 4, :o2, 29261887, 12
-
1
tz.transition 1964, 10, :o1, 29264071, 12
-
1
tz.transition 1965, 4, :o2, 29266255, 12
-
1
tz.transition 1965, 10, :o1, 29268439, 12
-
1
tz.transition 1966, 4, :o4, 29270623, 12
-
1
tz.transition 1976, 9, :o1, 212544000
-
1
tz.transition 1977, 3, :o2, 228268800
-
1
tz.transition 1977, 9, :o1, 243993600
-
1
tz.transition 1978, 4, :o2, 260323200
-
1
tz.transition 1978, 10, :o1, 276048000
-
1
tz.transition 1979, 4, :o2, 291772800
-
1
tz.transition 1979, 9, :o1, 307501200
-
1
tz.transition 1980, 3, :o2, 323222400
-
1
tz.transition 1980, 9, :o1, 338950800
-
1
tz.transition 1981, 3, :o2, 354675600
-
1
tz.transition 1981, 9, :o1, 370400400
-
1
tz.transition 1982, 3, :o2, 386125200
-
1
tz.transition 1982, 9, :o1, 401850000
-
1
tz.transition 1983, 3, :o2, 417578400
-
1
tz.transition 1983, 9, :o1, 433299600
-
1
tz.transition 1984, 3, :o2, 449024400
-
1
tz.transition 1984, 9, :o1, 465354000
-
1
tz.transition 1985, 3, :o2, 481078800
-
1
tz.transition 1985, 9, :o1, 496803600
-
1
tz.transition 1986, 3, :o2, 512528400
-
1
tz.transition 1986, 9, :o1, 528253200
-
1
tz.transition 1987, 3, :o2, 543978000
-
1
tz.transition 1987, 9, :o1, 559702800
-
1
tz.transition 1988, 3, :o2, 575427600
-
1
tz.transition 1988, 9, :o1, 591152400
-
1
tz.transition 1989, 3, :o2, 606877200
-
1
tz.transition 1989, 9, :o1, 622602000
-
1
tz.transition 1990, 3, :o2, 638326800
-
1
tz.transition 1990, 9, :o1, 654656400
-
1
tz.transition 1991, 3, :o2, 670381200
-
1
tz.transition 1991, 9, :o1, 686106000
-
1
tz.transition 1992, 3, :o2, 701830800
-
1
tz.transition 1992, 9, :o4, 717555600
-
1
tz.transition 1993, 3, :o5, 733280400
-
1
tz.transition 1993, 9, :o4, 749005200
-
1
tz.transition 1994, 3, :o5, 764730000
-
1
tz.transition 1994, 9, :o4, 780454800
-
1
tz.transition 1995, 3, :o5, 796179600
-
1
tz.transition 1995, 9, :o4, 811904400
-
1
tz.transition 1996, 3, :o2, 828234000
-
1
tz.transition 1996, 10, :o1, 846378000
-
1
tz.transition 1997, 3, :o2, 859683600
-
1
tz.transition 1997, 10, :o1, 877827600
-
1
tz.transition 1998, 3, :o2, 891133200
-
1
tz.transition 1998, 10, :o1, 909277200
-
1
tz.transition 1999, 3, :o2, 922582800
-
1
tz.transition 1999, 10, :o1, 941331600
-
1
tz.transition 2000, 3, :o2, 954032400
-
1
tz.transition 2000, 10, :o1, 972781200
-
1
tz.transition 2001, 3, :o2, 985482000
-
1
tz.transition 2001, 10, :o1, 1004230800
-
1
tz.transition 2002, 3, :o2, 1017536400
-
1
tz.transition 2002, 10, :o1, 1035680400
-
1
tz.transition 2003, 3, :o2, 1048986000
-
1
tz.transition 2003, 10, :o1, 1067130000
-
1
tz.transition 2004, 3, :o2, 1080435600
-
1
tz.transition 2004, 10, :o1, 1099184400
-
1
tz.transition 2005, 3, :o2, 1111885200
-
1
tz.transition 2005, 10, :o1, 1130634000
-
1
tz.transition 2006, 3, :o2, 1143334800
-
1
tz.transition 2006, 10, :o1, 1162083600
-
1
tz.transition 2007, 3, :o2, 1174784400
-
1
tz.transition 2007, 10, :o1, 1193533200
-
1
tz.transition 2008, 3, :o2, 1206838800
-
1
tz.transition 2008, 10, :o1, 1224982800
-
1
tz.transition 2009, 3, :o2, 1238288400
-
1
tz.transition 2009, 10, :o1, 1256432400
-
1
tz.transition 2010, 3, :o2, 1269738000
-
1
tz.transition 2010, 10, :o1, 1288486800
-
1
tz.transition 2011, 3, :o2, 1301187600
-
1
tz.transition 2011, 10, :o1, 1319936400
-
1
tz.transition 2012, 3, :o2, 1332637200
-
1
tz.transition 2012, 10, :o1, 1351386000
-
1
tz.transition 2013, 3, :o2, 1364691600
-
1
tz.transition 2013, 10, :o1, 1382835600
-
1
tz.transition 2014, 3, :o2, 1396141200
-
1
tz.transition 2014, 10, :o1, 1414285200
-
1
tz.transition 2015, 3, :o2, 1427590800
-
1
tz.transition 2015, 10, :o1, 1445734800
-
1
tz.transition 2016, 3, :o2, 1459040400
-
1
tz.transition 2016, 10, :o1, 1477789200
-
1
tz.transition 2017, 3, :o2, 1490490000
-
1
tz.transition 2017, 10, :o1, 1509238800
-
1
tz.transition 2018, 3, :o2, 1521939600
-
1
tz.transition 2018, 10, :o1, 1540688400
-
1
tz.transition 2019, 3, :o2, 1553994000
-
1
tz.transition 2019, 10, :o1, 1572138000
-
1
tz.transition 2020, 3, :o2, 1585443600
-
1
tz.transition 2020, 10, :o1, 1603587600
-
1
tz.transition 2021, 3, :o2, 1616893200
-
1
tz.transition 2021, 10, :o1, 1635642000
-
1
tz.transition 2022, 3, :o2, 1648342800
-
1
tz.transition 2022, 10, :o1, 1667091600
-
1
tz.transition 2023, 3, :o2, 1679792400
-
1
tz.transition 2023, 10, :o1, 1698541200
-
1
tz.transition 2024, 3, :o2, 1711846800
-
1
tz.transition 2024, 10, :o1, 1729990800
-
1
tz.transition 2025, 3, :o2, 1743296400
-
1
tz.transition 2025, 10, :o1, 1761440400
-
1
tz.transition 2026, 3, :o2, 1774746000
-
1
tz.transition 2026, 10, :o1, 1792890000
-
1
tz.transition 2027, 3, :o2, 1806195600
-
1
tz.transition 2027, 10, :o1, 1824944400
-
1
tz.transition 2028, 3, :o2, 1837645200
-
1
tz.transition 2028, 10, :o1, 1856394000
-
1
tz.transition 2029, 3, :o2, 1869094800
-
1
tz.transition 2029, 10, :o1, 1887843600
-
1
tz.transition 2030, 3, :o2, 1901149200
-
1
tz.transition 2030, 10, :o1, 1919293200
-
1
tz.transition 2031, 3, :o2, 1932598800
-
1
tz.transition 2031, 10, :o1, 1950742800
-
1
tz.transition 2032, 3, :o2, 1964048400
-
1
tz.transition 2032, 10, :o1, 1982797200
-
1
tz.transition 2033, 3, :o2, 1995498000
-
1
tz.transition 2033, 10, :o1, 2014246800
-
1
tz.transition 2034, 3, :o2, 2026947600
-
1
tz.transition 2034, 10, :o1, 2045696400
-
1
tz.transition 2035, 3, :o2, 2058397200
-
1
tz.transition 2035, 10, :o1, 2077146000
-
1
tz.transition 2036, 3, :o2, 2090451600
-
1
tz.transition 2036, 10, :o1, 2108595600
-
1
tz.transition 2037, 3, :o2, 2121901200
-
1
tz.transition 2037, 10, :o1, 2140045200
-
1
tz.transition 2038, 3, :o2, 59172253, 24
-
1
tz.transition 2038, 10, :o1, 59177461, 24
-
1
tz.transition 2039, 3, :o2, 59180989, 24
-
1
tz.transition 2039, 10, :o1, 59186197, 24
-
1
tz.transition 2040, 3, :o2, 59189725, 24
-
1
tz.transition 2040, 10, :o1, 59194933, 24
-
1
tz.transition 2041, 3, :o2, 59198629, 24
-
1
tz.transition 2041, 10, :o1, 59203669, 24
-
1
tz.transition 2042, 3, :o2, 59207365, 24
-
1
tz.transition 2042, 10, :o1, 59212405, 24
-
1
tz.transition 2043, 3, :o2, 59216101, 24
-
1
tz.transition 2043, 10, :o1, 59221141, 24
-
1
tz.transition 2044, 3, :o2, 59224837, 24
-
1
tz.transition 2044, 10, :o1, 59230045, 24
-
1
tz.transition 2045, 3, :o2, 59233573, 24
-
1
tz.transition 2045, 10, :o1, 59238781, 24
-
1
tz.transition 2046, 3, :o2, 59242309, 24
-
1
tz.transition 2046, 10, :o1, 59247517, 24
-
1
tz.transition 2047, 3, :o2, 59251213, 24
-
1
tz.transition 2047, 10, :o1, 59256253, 24
-
1
tz.transition 2048, 3, :o2, 59259949, 24
-
1
tz.transition 2048, 10, :o1, 59264989, 24
-
1
tz.transition 2049, 3, :o2, 59268685, 24
-
1
tz.transition 2049, 10, :o1, 59273893, 24
-
1
tz.transition 2050, 3, :o2, 59277421, 24
-
1
tz.transition 2050, 10, :o1, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Ljubljana
-
1
include TimezoneDefinition
-
-
1
linked_timezone 'Europe/Ljubljana', 'Europe/Belgrade'
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module London
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/London' do |tz|
-
1
tz.offset :o0, -75, 0, :LMT
-
1
tz.offset :o1, 0, 0, :GMT
-
1
tz.offset :o2, 0, 3600, :BST
-
1
tz.offset :o3, 0, 7200, :BDST
-
1
tz.offset :o4, 3600, 0, :BST
-
-
1
tz.transition 1847, 12, :o1, 2760187969, 1152
-
1
tz.transition 1916, 5, :o2, 29052055, 12
-
1
tz.transition 1916, 10, :o1, 29053651, 12
-
1
tz.transition 1917, 4, :o2, 29055919, 12
-
1
tz.transition 1917, 9, :o1, 29057863, 12
-
1
tz.transition 1918, 3, :o2, 29060119, 12
-
1
tz.transition 1918, 9, :o1, 29062399, 12
-
1
tz.transition 1919, 3, :o2, 29064571, 12
-
1
tz.transition 1919, 9, :o1, 29066767, 12
-
1
tz.transition 1920, 3, :o2, 29068939, 12
-
1
tz.transition 1920, 10, :o1, 29071471, 12
-
1
tz.transition 1921, 4, :o2, 29073391, 12
-
1
tz.transition 1921, 10, :o1, 29075587, 12
-
1
tz.transition 1922, 3, :o2, 29077675, 12
-
1
tz.transition 1922, 10, :o1, 29080027, 12
-
1
tz.transition 1923, 4, :o2, 29082379, 12
-
1
tz.transition 1923, 9, :o1, 29084143, 12
-
1
tz.transition 1924, 4, :o2, 29086663, 12
-
1
tz.transition 1924, 9, :o1, 29088595, 12
-
1
tz.transition 1925, 4, :o2, 29091115, 12
-
1
tz.transition 1925, 10, :o1, 29093131, 12
-
1
tz.transition 1926, 4, :o2, 29095483, 12
-
1
tz.transition 1926, 10, :o1, 29097499, 12
-
1
tz.transition 1927, 4, :o2, 29099767, 12
-
1
tz.transition 1927, 10, :o1, 29101867, 12
-
1
tz.transition 1928, 4, :o2, 29104303, 12
-
1
tz.transition 1928, 10, :o1, 29106319, 12
-
1
tz.transition 1929, 4, :o2, 29108671, 12
-
1
tz.transition 1929, 10, :o1, 29110687, 12
-
1
tz.transition 1930, 4, :o2, 29112955, 12
-
1
tz.transition 1930, 10, :o1, 29115055, 12
-
1
tz.transition 1931, 4, :o2, 29117407, 12
-
1
tz.transition 1931, 10, :o1, 29119423, 12
-
1
tz.transition 1932, 4, :o2, 29121775, 12
-
1
tz.transition 1932, 10, :o1, 29123791, 12
-
1
tz.transition 1933, 4, :o2, 29126059, 12
-
1
tz.transition 1933, 10, :o1, 29128243, 12
-
1
tz.transition 1934, 4, :o2, 29130595, 12
-
1
tz.transition 1934, 10, :o1, 29132611, 12
-
1
tz.transition 1935, 4, :o2, 29134879, 12
-
1
tz.transition 1935, 10, :o1, 29136979, 12
-
1
tz.transition 1936, 4, :o2, 29139331, 12
-
1
tz.transition 1936, 10, :o1, 29141347, 12
-
1
tz.transition 1937, 4, :o2, 29143699, 12
-
1
tz.transition 1937, 10, :o1, 29145715, 12
-
1
tz.transition 1938, 4, :o2, 29147983, 12
-
1
tz.transition 1938, 10, :o1, 29150083, 12
-
1
tz.transition 1939, 4, :o2, 29152435, 12
-
1
tz.transition 1939, 11, :o1, 29155039, 12
-
1
tz.transition 1940, 2, :o2, 29156215, 12
-
1
tz.transition 1941, 5, :o3, 58322845, 24
-
1
tz.transition 1941, 8, :o2, 58325197, 24
-
1
tz.transition 1942, 4, :o3, 58330909, 24
-
1
tz.transition 1942, 8, :o2, 58333933, 24
-
1
tz.transition 1943, 4, :o3, 58339645, 24
-
1
tz.transition 1943, 8, :o2, 58342837, 24
-
1
tz.transition 1944, 4, :o3, 58348381, 24
-
1
tz.transition 1944, 9, :o2, 58352413, 24
-
1
tz.transition 1945, 4, :o3, 58357141, 24
-
1
tz.transition 1945, 7, :o2, 58359637, 24
-
1
tz.transition 1945, 10, :o1, 29180827, 12
-
1
tz.transition 1946, 4, :o2, 29183095, 12
-
1
tz.transition 1946, 10, :o1, 29185195, 12
-
1
tz.transition 1947, 3, :o2, 29187127, 12
-
1
tz.transition 1947, 4, :o3, 58374925, 24
-
1
tz.transition 1947, 8, :o2, 58377781, 24
-
1
tz.transition 1947, 11, :o1, 29189899, 12
-
1
tz.transition 1948, 3, :o2, 29191495, 12
-
1
tz.transition 1948, 10, :o1, 29194267, 12
-
1
tz.transition 1949, 4, :o2, 29196115, 12
-
1
tz.transition 1949, 10, :o1, 29198635, 12
-
1
tz.transition 1950, 4, :o2, 29200651, 12
-
1
tz.transition 1950, 10, :o1, 29202919, 12
-
1
tz.transition 1951, 4, :o2, 29205019, 12
-
1
tz.transition 1951, 10, :o1, 29207287, 12
-
1
tz.transition 1952, 4, :o2, 29209471, 12
-
1
tz.transition 1952, 10, :o1, 29211739, 12
-
1
tz.transition 1953, 4, :o2, 29213839, 12
-
1
tz.transition 1953, 10, :o1, 29215855, 12
-
1
tz.transition 1954, 4, :o2, 29218123, 12
-
1
tz.transition 1954, 10, :o1, 29220223, 12
-
1
tz.transition 1955, 4, :o2, 29222575, 12
-
1
tz.transition 1955, 10, :o1, 29224591, 12
-
1
tz.transition 1956, 4, :o2, 29227027, 12
-
1
tz.transition 1956, 10, :o1, 29229043, 12
-
1
tz.transition 1957, 4, :o2, 29231311, 12
-
1
tz.transition 1957, 10, :o1, 29233411, 12
-
1
tz.transition 1958, 4, :o2, 29235763, 12
-
1
tz.transition 1958, 10, :o1, 29237779, 12
-
1
tz.transition 1959, 4, :o2, 29240131, 12
-
1
tz.transition 1959, 10, :o1, 29242147, 12
-
1
tz.transition 1960, 4, :o2, 29244415, 12
-
1
tz.transition 1960, 10, :o1, 29246515, 12
-
1
tz.transition 1961, 3, :o2, 29248615, 12
-
1
tz.transition 1961, 10, :o1, 29251219, 12
-
1
tz.transition 1962, 3, :o2, 29252983, 12
-
1
tz.transition 1962, 10, :o1, 29255587, 12
-
1
tz.transition 1963, 3, :o2, 29257435, 12
-
1
tz.transition 1963, 10, :o1, 29259955, 12
-
1
tz.transition 1964, 3, :o2, 29261719, 12
-
1
tz.transition 1964, 10, :o1, 29264323, 12
-
1
tz.transition 1965, 3, :o2, 29266087, 12
-
1
tz.transition 1965, 10, :o1, 29268691, 12
-
1
tz.transition 1966, 3, :o2, 29270455, 12
-
1
tz.transition 1966, 10, :o1, 29273059, 12
-
1
tz.transition 1967, 3, :o2, 29274823, 12
-
1
tz.transition 1967, 10, :o1, 29277511, 12
-
1
tz.transition 1968, 2, :o2, 29278855, 12
-
1
tz.transition 1968, 10, :o4, 58563755, 24
-
1
tz.transition 1971, 10, :o1, 57722400
-
1
tz.transition 1972, 3, :o2, 69818400
-
1
tz.transition 1972, 10, :o1, 89172000
-
1
tz.transition 1973, 3, :o2, 101268000
-
1
tz.transition 1973, 10, :o1, 120621600
-
1
tz.transition 1974, 3, :o2, 132717600
-
1
tz.transition 1974, 10, :o1, 152071200
-
1
tz.transition 1975, 3, :o2, 164167200
-
1
tz.transition 1975, 10, :o1, 183520800
-
1
tz.transition 1976, 3, :o2, 196221600
-
1
tz.transition 1976, 10, :o1, 214970400
-
1
tz.transition 1977, 3, :o2, 227671200
-
1
tz.transition 1977, 10, :o1, 246420000
-
1
tz.transition 1978, 3, :o2, 259120800
-
1
tz.transition 1978, 10, :o1, 278474400
-
1
tz.transition 1979, 3, :o2, 290570400
-
1
tz.transition 1979, 10, :o1, 309924000
-
1
tz.transition 1980, 3, :o2, 322020000
-
1
tz.transition 1980, 10, :o1, 341373600
-
1
tz.transition 1981, 3, :o2, 354675600
-
1
tz.transition 1981, 10, :o1, 372819600
-
1
tz.transition 1982, 3, :o2, 386125200
-
1
tz.transition 1982, 10, :o1, 404269200
-
1
tz.transition 1983, 3, :o2, 417574800
-
1
tz.transition 1983, 10, :o1, 435718800
-
1
tz.transition 1984, 3, :o2, 449024400
-
1
tz.transition 1984, 10, :o1, 467773200
-
1
tz.transition 1985, 3, :o2, 481078800
-
1
tz.transition 1985, 10, :o1, 499222800
-
1
tz.transition 1986, 3, :o2, 512528400
-
1
tz.transition 1986, 10, :o1, 530672400
-
1
tz.transition 1987, 3, :o2, 543978000
-
1
tz.transition 1987, 10, :o1, 562122000
-
1
tz.transition 1988, 3, :o2, 575427600
-
1
tz.transition 1988, 10, :o1, 593571600
-
1
tz.transition 1989, 3, :o2, 606877200
-
1
tz.transition 1989, 10, :o1, 625626000
-
1
tz.transition 1990, 3, :o2, 638326800
-
1
tz.transition 1990, 10, :o1, 657075600
-
1
tz.transition 1991, 3, :o2, 670381200
-
1
tz.transition 1991, 10, :o1, 688525200
-
1
tz.transition 1992, 3, :o2, 701830800
-
1
tz.transition 1992, 10, :o1, 719974800
-
1
tz.transition 1993, 3, :o2, 733280400
-
1
tz.transition 1993, 10, :o1, 751424400
-
1
tz.transition 1994, 3, :o2, 764730000
-
1
tz.transition 1994, 10, :o1, 782874000
-
1
tz.transition 1995, 3, :o2, 796179600
-
1
tz.transition 1995, 10, :o1, 814323600
-
1
tz.transition 1996, 3, :o2, 828234000
-
1
tz.transition 1996, 10, :o1, 846378000
-
1
tz.transition 1997, 3, :o2, 859683600
-
1
tz.transition 1997, 10, :o1, 877827600
-
1
tz.transition 1998, 3, :o2, 891133200
-
1
tz.transition 1998, 10, :o1, 909277200
-
1
tz.transition 1999, 3, :o2, 922582800
-
1
tz.transition 1999, 10, :o1, 941331600
-
1
tz.transition 2000, 3, :o2, 954032400
-
1
tz.transition 2000, 10, :o1, 972781200
-
1
tz.transition 2001, 3, :o2, 985482000
-
1
tz.transition 2001, 10, :o1, 1004230800
-
1
tz.transition 2002, 3, :o2, 1017536400
-
1
tz.transition 2002, 10, :o1, 1035680400
-
1
tz.transition 2003, 3, :o2, 1048986000
-
1
tz.transition 2003, 10, :o1, 1067130000
-
1
tz.transition 2004, 3, :o2, 1080435600
-
1
tz.transition 2004, 10, :o1, 1099184400
-
1
tz.transition 2005, 3, :o2, 1111885200
-
1
tz.transition 2005, 10, :o1, 1130634000
-
1
tz.transition 2006, 3, :o2, 1143334800
-
1
tz.transition 2006, 10, :o1, 1162083600
-
1
tz.transition 2007, 3, :o2, 1174784400
-
1
tz.transition 2007, 10, :o1, 1193533200
-
1
tz.transition 2008, 3, :o2, 1206838800
-
1
tz.transition 2008, 10, :o1, 1224982800
-
1
tz.transition 2009, 3, :o2, 1238288400
-
1
tz.transition 2009, 10, :o1, 1256432400
-
1
tz.transition 2010, 3, :o2, 1269738000
-
1
tz.transition 2010, 10, :o1, 1288486800
-
1
tz.transition 2011, 3, :o2, 1301187600
-
1
tz.transition 2011, 10, :o1, 1319936400
-
1
tz.transition 2012, 3, :o2, 1332637200
-
1
tz.transition 2012, 10, :o1, 1351386000
-
1
tz.transition 2013, 3, :o2, 1364691600
-
1
tz.transition 2013, 10, :o1, 1382835600
-
1
tz.transition 2014, 3, :o2, 1396141200
-
1
tz.transition 2014, 10, :o1, 1414285200
-
1
tz.transition 2015, 3, :o2, 1427590800
-
1
tz.transition 2015, 10, :o1, 1445734800
-
1
tz.transition 2016, 3, :o2, 1459040400
-
1
tz.transition 2016, 10, :o1, 1477789200
-
1
tz.transition 2017, 3, :o2, 1490490000
-
1
tz.transition 2017, 10, :o1, 1509238800
-
1
tz.transition 2018, 3, :o2, 1521939600
-
1
tz.transition 2018, 10, :o1, 1540688400
-
1
tz.transition 2019, 3, :o2, 1553994000
-
1
tz.transition 2019, 10, :o1, 1572138000
-
1
tz.transition 2020, 3, :o2, 1585443600
-
1
tz.transition 2020, 10, :o1, 1603587600
-
1
tz.transition 2021, 3, :o2, 1616893200
-
1
tz.transition 2021, 10, :o1, 1635642000
-
1
tz.transition 2022, 3, :o2, 1648342800
-
1
tz.transition 2022, 10, :o1, 1667091600
-
1
tz.transition 2023, 3, :o2, 1679792400
-
1
tz.transition 2023, 10, :o1, 1698541200
-
1
tz.transition 2024, 3, :o2, 1711846800
-
1
tz.transition 2024, 10, :o1, 1729990800
-
1
tz.transition 2025, 3, :o2, 1743296400
-
1
tz.transition 2025, 10, :o1, 1761440400
-
1
tz.transition 2026, 3, :o2, 1774746000
-
1
tz.transition 2026, 10, :o1, 1792890000
-
1
tz.transition 2027, 3, :o2, 1806195600
-
1
tz.transition 2027, 10, :o1, 1824944400
-
1
tz.transition 2028, 3, :o2, 1837645200
-
1
tz.transition 2028, 10, :o1, 1856394000
-
1
tz.transition 2029, 3, :o2, 1869094800
-
1
tz.transition 2029, 10, :o1, 1887843600
-
1
tz.transition 2030, 3, :o2, 1901149200
-
1
tz.transition 2030, 10, :o1, 1919293200
-
1
tz.transition 2031, 3, :o2, 1932598800
-
1
tz.transition 2031, 10, :o1, 1950742800
-
1
tz.transition 2032, 3, :o2, 1964048400
-
1
tz.transition 2032, 10, :o1, 1982797200
-
1
tz.transition 2033, 3, :o2, 1995498000
-
1
tz.transition 2033, 10, :o1, 2014246800
-
1
tz.transition 2034, 3, :o2, 2026947600
-
1
tz.transition 2034, 10, :o1, 2045696400
-
1
tz.transition 2035, 3, :o2, 2058397200
-
1
tz.transition 2035, 10, :o1, 2077146000
-
1
tz.transition 2036, 3, :o2, 2090451600
-
1
tz.transition 2036, 10, :o1, 2108595600
-
1
tz.transition 2037, 3, :o2, 2121901200
-
1
tz.transition 2037, 10, :o1, 2140045200
-
1
tz.transition 2038, 3, :o2, 59172253, 24
-
1
tz.transition 2038, 10, :o1, 59177461, 24
-
1
tz.transition 2039, 3, :o2, 59180989, 24
-
1
tz.transition 2039, 10, :o1, 59186197, 24
-
1
tz.transition 2040, 3, :o2, 59189725, 24
-
1
tz.transition 2040, 10, :o1, 59194933, 24
-
1
tz.transition 2041, 3, :o2, 59198629, 24
-
1
tz.transition 2041, 10, :o1, 59203669, 24
-
1
tz.transition 2042, 3, :o2, 59207365, 24
-
1
tz.transition 2042, 10, :o1, 59212405, 24
-
1
tz.transition 2043, 3, :o2, 59216101, 24
-
1
tz.transition 2043, 10, :o1, 59221141, 24
-
1
tz.transition 2044, 3, :o2, 59224837, 24
-
1
tz.transition 2044, 10, :o1, 59230045, 24
-
1
tz.transition 2045, 3, :o2, 59233573, 24
-
1
tz.transition 2045, 10, :o1, 59238781, 24
-
1
tz.transition 2046, 3, :o2, 59242309, 24
-
1
tz.transition 2046, 10, :o1, 59247517, 24
-
1
tz.transition 2047, 3, :o2, 59251213, 24
-
1
tz.transition 2047, 10, :o1, 59256253, 24
-
1
tz.transition 2048, 3, :o2, 59259949, 24
-
1
tz.transition 2048, 10, :o1, 59264989, 24
-
1
tz.transition 2049, 3, :o2, 59268685, 24
-
1
tz.transition 2049, 10, :o1, 59273893, 24
-
1
tz.transition 2050, 3, :o2, 59277421, 24
-
1
tz.transition 2050, 10, :o1, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Madrid
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Madrid' do |tz|
-
1
tz.offset :o0, -884, 0, :LMT
-
1
tz.offset :o1, 0, 0, :WET
-
1
tz.offset :o2, 0, 3600, :WEST
-
1
tz.offset :o3, 0, 7200, :WEMT
-
1
tz.offset :o4, 3600, 0, :CET
-
1
tz.offset :o5, 3600, 3600, :CEST
-
-
1
tz.transition 1901, 1, :o1, 52172327021, 21600
-
1
tz.transition 1917, 5, :o2, 58112507, 24
-
1
tz.transition 1917, 10, :o1, 58116203, 24
-
1
tz.transition 1918, 4, :o2, 58120787, 24
-
1
tz.transition 1918, 10, :o1, 58124963, 24
-
1
tz.transition 1919, 4, :o2, 58129307, 24
-
1
tz.transition 1919, 10, :o1, 58133723, 24
-
1
tz.transition 1924, 4, :o2, 58173419, 24
-
1
tz.transition 1924, 10, :o1, 58177523, 24
-
1
tz.transition 1926, 4, :o2, 58190963, 24
-
1
tz.transition 1926, 10, :o1, 58194995, 24
-
1
tz.transition 1927, 4, :o2, 58199531, 24
-
1
tz.transition 1927, 10, :o1, 58203731, 24
-
1
tz.transition 1928, 4, :o2, 58208435, 24
-
1
tz.transition 1928, 10, :o1, 58212635, 24
-
1
tz.transition 1929, 4, :o2, 58217339, 24
-
1
tz.transition 1929, 10, :o1, 58221371, 24
-
1
tz.transition 1937, 5, :o2, 58288235, 24
-
1
tz.transition 1937, 10, :o1, 58291427, 24
-
1
tz.transition 1938, 3, :o2, 58295531, 24
-
1
tz.transition 1938, 10, :o1, 58300163, 24
-
1
tz.transition 1939, 4, :o2, 58304867, 24
-
1
tz.transition 1939, 10, :o1, 58309067, 24
-
1
tz.transition 1940, 3, :o2, 58312931, 24
-
1
tz.transition 1942, 5, :o3, 29165789, 12
-
1
tz.transition 1942, 9, :o2, 29167253, 12
-
1
tz.transition 1943, 4, :o3, 29169989, 12
-
1
tz.transition 1943, 10, :o2, 29172017, 12
-
1
tz.transition 1944, 4, :o3, 29174357, 12
-
1
tz.transition 1944, 10, :o2, 29176493, 12
-
1
tz.transition 1945, 4, :o3, 29178725, 12
-
1
tz.transition 1945, 9, :o2, 58361483, 24
-
1
tz.transition 1946, 4, :o3, 29183093, 12
-
1
tz.transition 1946, 9, :o4, 29185121, 12
-
1
tz.transition 1949, 4, :o5, 29196449, 12
-
1
tz.transition 1949, 9, :o4, 58396547, 24
-
1
tz.transition 1974, 4, :o5, 135122400
-
1
tz.transition 1974, 10, :o4, 150246000
-
1
tz.transition 1975, 4, :o5, 167176800
-
1
tz.transition 1975, 10, :o4, 181695600
-
1
tz.transition 1976, 3, :o5, 196812000
-
1
tz.transition 1976, 9, :o4, 212540400
-
1
tz.transition 1977, 4, :o5, 228866400
-
1
tz.transition 1977, 9, :o4, 243990000
-
1
tz.transition 1978, 4, :o5, 260402400
-
1
tz.transition 1978, 9, :o4, 276044400
-
1
tz.transition 1979, 4, :o5, 291776400
-
1
tz.transition 1979, 9, :o4, 307501200
-
1
tz.transition 1980, 4, :o5, 323830800
-
1
tz.transition 1980, 9, :o4, 338950800
-
1
tz.transition 1981, 3, :o5, 354675600
-
1
tz.transition 1981, 9, :o4, 370400400
-
1
tz.transition 1982, 3, :o5, 386125200
-
1
tz.transition 1982, 9, :o4, 401850000
-
1
tz.transition 1983, 3, :o5, 417574800
-
1
tz.transition 1983, 9, :o4, 433299600
-
1
tz.transition 1984, 3, :o5, 449024400
-
1
tz.transition 1984, 9, :o4, 465354000
-
1
tz.transition 1985, 3, :o5, 481078800
-
1
tz.transition 1985, 9, :o4, 496803600
-
1
tz.transition 1986, 3, :o5, 512528400
-
1
tz.transition 1986, 9, :o4, 528253200
-
1
tz.transition 1987, 3, :o5, 543978000
-
1
tz.transition 1987, 9, :o4, 559702800
-
1
tz.transition 1988, 3, :o5, 575427600
-
1
tz.transition 1988, 9, :o4, 591152400
-
1
tz.transition 1989, 3, :o5, 606877200
-
1
tz.transition 1989, 9, :o4, 622602000
-
1
tz.transition 1990, 3, :o5, 638326800
-
1
tz.transition 1990, 9, :o4, 654656400
-
1
tz.transition 1991, 3, :o5, 670381200
-
1
tz.transition 1991, 9, :o4, 686106000
-
1
tz.transition 1992, 3, :o5, 701830800
-
1
tz.transition 1992, 9, :o4, 717555600
-
1
tz.transition 1993, 3, :o5, 733280400
-
1
tz.transition 1993, 9, :o4, 749005200
-
1
tz.transition 1994, 3, :o5, 764730000
-
1
tz.transition 1994, 9, :o4, 780454800
-
1
tz.transition 1995, 3, :o5, 796179600
-
1
tz.transition 1995, 9, :o4, 811904400
-
1
tz.transition 1996, 3, :o5, 828234000
-
1
tz.transition 1996, 10, :o4, 846378000
-
1
tz.transition 1997, 3, :o5, 859683600
-
1
tz.transition 1997, 10, :o4, 877827600
-
1
tz.transition 1998, 3, :o5, 891133200
-
1
tz.transition 1998, 10, :o4, 909277200
-
1
tz.transition 1999, 3, :o5, 922582800
-
1
tz.transition 1999, 10, :o4, 941331600
-
1
tz.transition 2000, 3, :o5, 954032400
-
1
tz.transition 2000, 10, :o4, 972781200
-
1
tz.transition 2001, 3, :o5, 985482000
-
1
tz.transition 2001, 10, :o4, 1004230800
-
1
tz.transition 2002, 3, :o5, 1017536400
-
1
tz.transition 2002, 10, :o4, 1035680400
-
1
tz.transition 2003, 3, :o5, 1048986000
-
1
tz.transition 2003, 10, :o4, 1067130000
-
1
tz.transition 2004, 3, :o5, 1080435600
-
1
tz.transition 2004, 10, :o4, 1099184400
-
1
tz.transition 2005, 3, :o5, 1111885200
-
1
tz.transition 2005, 10, :o4, 1130634000
-
1
tz.transition 2006, 3, :o5, 1143334800
-
1
tz.transition 2006, 10, :o4, 1162083600
-
1
tz.transition 2007, 3, :o5, 1174784400
-
1
tz.transition 2007, 10, :o4, 1193533200
-
1
tz.transition 2008, 3, :o5, 1206838800
-
1
tz.transition 2008, 10, :o4, 1224982800
-
1
tz.transition 2009, 3, :o5, 1238288400
-
1
tz.transition 2009, 10, :o4, 1256432400
-
1
tz.transition 2010, 3, :o5, 1269738000
-
1
tz.transition 2010, 10, :o4, 1288486800
-
1
tz.transition 2011, 3, :o5, 1301187600
-
1
tz.transition 2011, 10, :o4, 1319936400
-
1
tz.transition 2012, 3, :o5, 1332637200
-
1
tz.transition 2012, 10, :o4, 1351386000
-
1
tz.transition 2013, 3, :o5, 1364691600
-
1
tz.transition 2013, 10, :o4, 1382835600
-
1
tz.transition 2014, 3, :o5, 1396141200
-
1
tz.transition 2014, 10, :o4, 1414285200
-
1
tz.transition 2015, 3, :o5, 1427590800
-
1
tz.transition 2015, 10, :o4, 1445734800
-
1
tz.transition 2016, 3, :o5, 1459040400
-
1
tz.transition 2016, 10, :o4, 1477789200
-
1
tz.transition 2017, 3, :o5, 1490490000
-
1
tz.transition 2017, 10, :o4, 1509238800
-
1
tz.transition 2018, 3, :o5, 1521939600
-
1
tz.transition 2018, 10, :o4, 1540688400
-
1
tz.transition 2019, 3, :o5, 1553994000
-
1
tz.transition 2019, 10, :o4, 1572138000
-
1
tz.transition 2020, 3, :o5, 1585443600
-
1
tz.transition 2020, 10, :o4, 1603587600
-
1
tz.transition 2021, 3, :o5, 1616893200
-
1
tz.transition 2021, 10, :o4, 1635642000
-
1
tz.transition 2022, 3, :o5, 1648342800
-
1
tz.transition 2022, 10, :o4, 1667091600
-
1
tz.transition 2023, 3, :o5, 1679792400
-
1
tz.transition 2023, 10, :o4, 1698541200
-
1
tz.transition 2024, 3, :o5, 1711846800
-
1
tz.transition 2024, 10, :o4, 1729990800
-
1
tz.transition 2025, 3, :o5, 1743296400
-
1
tz.transition 2025, 10, :o4, 1761440400
-
1
tz.transition 2026, 3, :o5, 1774746000
-
1
tz.transition 2026, 10, :o4, 1792890000
-
1
tz.transition 2027, 3, :o5, 1806195600
-
1
tz.transition 2027, 10, :o4, 1824944400
-
1
tz.transition 2028, 3, :o5, 1837645200
-
1
tz.transition 2028, 10, :o4, 1856394000
-
1
tz.transition 2029, 3, :o5, 1869094800
-
1
tz.transition 2029, 10, :o4, 1887843600
-
1
tz.transition 2030, 3, :o5, 1901149200
-
1
tz.transition 2030, 10, :o4, 1919293200
-
1
tz.transition 2031, 3, :o5, 1932598800
-
1
tz.transition 2031, 10, :o4, 1950742800
-
1
tz.transition 2032, 3, :o5, 1964048400
-
1
tz.transition 2032, 10, :o4, 1982797200
-
1
tz.transition 2033, 3, :o5, 1995498000
-
1
tz.transition 2033, 10, :o4, 2014246800
-
1
tz.transition 2034, 3, :o5, 2026947600
-
1
tz.transition 2034, 10, :o4, 2045696400
-
1
tz.transition 2035, 3, :o5, 2058397200
-
1
tz.transition 2035, 10, :o4, 2077146000
-
1
tz.transition 2036, 3, :o5, 2090451600
-
1
tz.transition 2036, 10, :o4, 2108595600
-
1
tz.transition 2037, 3, :o5, 2121901200
-
1
tz.transition 2037, 10, :o4, 2140045200
-
1
tz.transition 2038, 3, :o5, 59172253, 24
-
1
tz.transition 2038, 10, :o4, 59177461, 24
-
1
tz.transition 2039, 3, :o5, 59180989, 24
-
1
tz.transition 2039, 10, :o4, 59186197, 24
-
1
tz.transition 2040, 3, :o5, 59189725, 24
-
1
tz.transition 2040, 10, :o4, 59194933, 24
-
1
tz.transition 2041, 3, :o5, 59198629, 24
-
1
tz.transition 2041, 10, :o4, 59203669, 24
-
1
tz.transition 2042, 3, :o5, 59207365, 24
-
1
tz.transition 2042, 10, :o4, 59212405, 24
-
1
tz.transition 2043, 3, :o5, 59216101, 24
-
1
tz.transition 2043, 10, :o4, 59221141, 24
-
1
tz.transition 2044, 3, :o5, 59224837, 24
-
1
tz.transition 2044, 10, :o4, 59230045, 24
-
1
tz.transition 2045, 3, :o5, 59233573, 24
-
1
tz.transition 2045, 10, :o4, 59238781, 24
-
1
tz.transition 2046, 3, :o5, 59242309, 24
-
1
tz.transition 2046, 10, :o4, 59247517, 24
-
1
tz.transition 2047, 3, :o5, 59251213, 24
-
1
tz.transition 2047, 10, :o4, 59256253, 24
-
1
tz.transition 2048, 3, :o5, 59259949, 24
-
1
tz.transition 2048, 10, :o4, 59264989, 24
-
1
tz.transition 2049, 3, :o5, 59268685, 24
-
1
tz.transition 2049, 10, :o4, 59273893, 24
-
1
tz.transition 2050, 3, :o5, 59277421, 24
-
1
tz.transition 2050, 10, :o4, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Minsk
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Minsk' do |tz|
-
1
tz.offset :o0, 6616, 0, :LMT
-
1
tz.offset :o1, 6600, 0, :MMT
-
1
tz.offset :o2, 7200, 0, :EET
-
1
tz.offset :o3, 10800, 0, :MSK
-
1
tz.offset :o4, 3600, 3600, :CEST
-
1
tz.offset :o5, 3600, 0, :CET
-
1
tz.offset :o6, 10800, 3600, :MSD
-
1
tz.offset :o7, 7200, 3600, :EEST
-
1
tz.offset :o8, 10800, 0, :FET
-
-
1
tz.transition 1879, 12, :o1, 26003326573, 10800
-
1
tz.transition 1924, 5, :o2, 349042669, 144
-
1
tz.transition 1930, 6, :o3, 29113781, 12
-
1
tz.transition 1941, 6, :o4, 19441387, 8
-
1
tz.transition 1942, 11, :o5, 58335973, 24
-
1
tz.transition 1943, 3, :o4, 58339501, 24
-
1
tz.transition 1943, 10, :o5, 58344037, 24
-
1
tz.transition 1944, 4, :o4, 58348405, 24
-
1
tz.transition 1944, 7, :o3, 29175293, 12
-
1
tz.transition 1981, 3, :o6, 354920400
-
1
tz.transition 1981, 9, :o3, 370728000
-
1
tz.transition 1982, 3, :o6, 386456400
-
1
tz.transition 1982, 9, :o3, 402264000
-
1
tz.transition 1983, 3, :o6, 417992400
-
1
tz.transition 1983, 9, :o3, 433800000
-
1
tz.transition 1984, 3, :o6, 449614800
-
1
tz.transition 1984, 9, :o3, 465346800
-
1
tz.transition 1985, 3, :o6, 481071600
-
1
tz.transition 1985, 9, :o3, 496796400
-
1
tz.transition 1986, 3, :o6, 512521200
-
1
tz.transition 1986, 9, :o3, 528246000
-
1
tz.transition 1987, 3, :o6, 543970800
-
1
tz.transition 1987, 9, :o3, 559695600
-
1
tz.transition 1988, 3, :o6, 575420400
-
1
tz.transition 1988, 9, :o3, 591145200
-
1
tz.transition 1989, 3, :o6, 606870000
-
1
tz.transition 1989, 9, :o3, 622594800
-
1
tz.transition 1991, 3, :o7, 670374000
-
1
tz.transition 1991, 9, :o2, 686102400
-
1
tz.transition 1992, 3, :o7, 701820000
-
1
tz.transition 1992, 9, :o2, 717544800
-
1
tz.transition 1993, 3, :o7, 733276800
-
1
tz.transition 1993, 9, :o2, 749001600
-
1
tz.transition 1994, 3, :o7, 764726400
-
1
tz.transition 1994, 9, :o2, 780451200
-
1
tz.transition 1995, 3, :o7, 796176000
-
1
tz.transition 1995, 9, :o2, 811900800
-
1
tz.transition 1996, 3, :o7, 828230400
-
1
tz.transition 1996, 10, :o2, 846374400
-
1
tz.transition 1997, 3, :o7, 859680000
-
1
tz.transition 1997, 10, :o2, 877824000
-
1
tz.transition 1998, 3, :o7, 891129600
-
1
tz.transition 1998, 10, :o2, 909273600
-
1
tz.transition 1999, 3, :o7, 922579200
-
1
tz.transition 1999, 10, :o2, 941328000
-
1
tz.transition 2000, 3, :o7, 954028800
-
1
tz.transition 2000, 10, :o2, 972777600
-
1
tz.transition 2001, 3, :o7, 985478400
-
1
tz.transition 2001, 10, :o2, 1004227200
-
1
tz.transition 2002, 3, :o7, 1017532800
-
1
tz.transition 2002, 10, :o2, 1035676800
-
1
tz.transition 2003, 3, :o7, 1048982400
-
1
tz.transition 2003, 10, :o2, 1067126400
-
1
tz.transition 2004, 3, :o7, 1080432000
-
1
tz.transition 2004, 10, :o2, 1099180800
-
1
tz.transition 2005, 3, :o7, 1111881600
-
1
tz.transition 2005, 10, :o2, 1130630400
-
1
tz.transition 2006, 3, :o7, 1143331200
-
1
tz.transition 2006, 10, :o2, 1162080000
-
1
tz.transition 2007, 3, :o7, 1174780800
-
1
tz.transition 2007, 10, :o2, 1193529600
-
1
tz.transition 2008, 3, :o7, 1206835200
-
1
tz.transition 2008, 10, :o2, 1224979200
-
1
tz.transition 2009, 3, :o7, 1238284800
-
1
tz.transition 2009, 10, :o2, 1256428800
-
1
tz.transition 2010, 3, :o7, 1269734400
-
1
tz.transition 2010, 10, :o2, 1288483200
-
1
tz.transition 2011, 3, :o8, 1301184000
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Moscow
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Moscow' do |tz|
-
1
tz.offset :o0, 9020, 0, :LMT
-
1
tz.offset :o1, 9000, 0, :MMT
-
1
tz.offset :o2, 9048, 0, :MMT
-
1
tz.offset :o3, 9048, 3600, :MST
-
1
tz.offset :o4, 9048, 7200, :MDST
-
1
tz.offset :o5, 10800, 3600, :MSD
-
1
tz.offset :o6, 10800, 0, :MSK
-
1
tz.offset :o7, 10800, 7200, :MSD
-
1
tz.offset :o8, 7200, 0, :EET
-
1
tz.offset :o9, 7200, 3600, :EEST
-
1
tz.offset :o10, 14400, 0, :MSK
-
-
1
tz.transition 1879, 12, :o1, 10401330509, 4320
-
1
tz.transition 1916, 7, :o2, 116210275, 48
-
1
tz.transition 1917, 7, :o3, 8717080873, 3600
-
1
tz.transition 1917, 12, :o2, 8717725273, 3600
-
1
tz.transition 1918, 5, :o4, 8718283123, 3600
-
1
tz.transition 1918, 9, :o3, 8718668473, 3600
-
1
tz.transition 1919, 5, :o4, 8719597123, 3600
-
1
tz.transition 1919, 6, :o5, 8719705423, 3600
-
1
tz.transition 1919, 8, :o6, 7266559, 3
-
1
tz.transition 1921, 2, :o5, 7268206, 3
-
1
tz.transition 1921, 3, :o7, 58146463, 24
-
1
tz.transition 1921, 8, :o5, 58150399, 24
-
1
tz.transition 1921, 9, :o6, 7268890, 3
-
1
tz.transition 1922, 9, :o8, 19386627, 8
-
1
tz.transition 1930, 6, :o6, 29113781, 12
-
1
tz.transition 1981, 3, :o5, 354920400
-
1
tz.transition 1981, 9, :o6, 370728000
-
1
tz.transition 1982, 3, :o5, 386456400
-
1
tz.transition 1982, 9, :o6, 402264000
-
1
tz.transition 1983, 3, :o5, 417992400
-
1
tz.transition 1983, 9, :o6, 433800000
-
1
tz.transition 1984, 3, :o5, 449614800
-
1
tz.transition 1984, 9, :o6, 465346800
-
1
tz.transition 1985, 3, :o5, 481071600
-
1
tz.transition 1985, 9, :o6, 496796400
-
1
tz.transition 1986, 3, :o5, 512521200
-
1
tz.transition 1986, 9, :o6, 528246000
-
1
tz.transition 1987, 3, :o5, 543970800
-
1
tz.transition 1987, 9, :o6, 559695600
-
1
tz.transition 1988, 3, :o5, 575420400
-
1
tz.transition 1988, 9, :o6, 591145200
-
1
tz.transition 1989, 3, :o5, 606870000
-
1
tz.transition 1989, 9, :o6, 622594800
-
1
tz.transition 1990, 3, :o5, 638319600
-
1
tz.transition 1990, 9, :o6, 654649200
-
1
tz.transition 1991, 3, :o9, 670374000
-
1
tz.transition 1991, 9, :o8, 686102400
-
1
tz.transition 1992, 1, :o6, 695779200
-
1
tz.transition 1992, 3, :o5, 701812800
-
1
tz.transition 1992, 9, :o6, 717534000
-
1
tz.transition 1993, 3, :o5, 733273200
-
1
tz.transition 1993, 9, :o6, 748998000
-
1
tz.transition 1994, 3, :o5, 764722800
-
1
tz.transition 1994, 9, :o6, 780447600
-
1
tz.transition 1995, 3, :o5, 796172400
-
1
tz.transition 1995, 9, :o6, 811897200
-
1
tz.transition 1996, 3, :o5, 828226800
-
1
tz.transition 1996, 10, :o6, 846370800
-
1
tz.transition 1997, 3, :o5, 859676400
-
1
tz.transition 1997, 10, :o6, 877820400
-
1
tz.transition 1998, 3, :o5, 891126000
-
1
tz.transition 1998, 10, :o6, 909270000
-
1
tz.transition 1999, 3, :o5, 922575600
-
1
tz.transition 1999, 10, :o6, 941324400
-
1
tz.transition 2000, 3, :o5, 954025200
-
1
tz.transition 2000, 10, :o6, 972774000
-
1
tz.transition 2001, 3, :o5, 985474800
-
1
tz.transition 2001, 10, :o6, 1004223600
-
1
tz.transition 2002, 3, :o5, 1017529200
-
1
tz.transition 2002, 10, :o6, 1035673200
-
1
tz.transition 2003, 3, :o5, 1048978800
-
1
tz.transition 2003, 10, :o6, 1067122800
-
1
tz.transition 2004, 3, :o5, 1080428400
-
1
tz.transition 2004, 10, :o6, 1099177200
-
1
tz.transition 2005, 3, :o5, 1111878000
-
1
tz.transition 2005, 10, :o6, 1130626800
-
1
tz.transition 2006, 3, :o5, 1143327600
-
1
tz.transition 2006, 10, :o6, 1162076400
-
1
tz.transition 2007, 3, :o5, 1174777200
-
1
tz.transition 2007, 10, :o6, 1193526000
-
1
tz.transition 2008, 3, :o5, 1206831600
-
1
tz.transition 2008, 10, :o6, 1224975600
-
1
tz.transition 2009, 3, :o5, 1238281200
-
1
tz.transition 2009, 10, :o6, 1256425200
-
1
tz.transition 2010, 3, :o5, 1269730800
-
1
tz.transition 2010, 10, :o6, 1288479600
-
1
tz.transition 2011, 3, :o10, 1301180400
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Paris
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Paris' do |tz|
-
1
tz.offset :o0, 561, 0, :LMT
-
1
tz.offset :o1, 561, 0, :PMT
-
1
tz.offset :o2, 0, 0, :WET
-
1
tz.offset :o3, 0, 3600, :WEST
-
1
tz.offset :o4, 3600, 3600, :CEST
-
1
tz.offset :o5, 3600, 0, :CET
-
1
tz.offset :o6, 0, 7200, :WEMT
-
-
1
tz.transition 1891, 3, :o1, 69460027033, 28800
-
1
tz.transition 1911, 3, :o2, 69670267033, 28800
-
1
tz.transition 1916, 6, :o3, 58104707, 24
-
1
tz.transition 1916, 10, :o2, 58107323, 24
-
1
tz.transition 1917, 3, :o3, 58111499, 24
-
1
tz.transition 1917, 10, :o2, 58116227, 24
-
1
tz.transition 1918, 3, :o3, 58119899, 24
-
1
tz.transition 1918, 10, :o2, 58124963, 24
-
1
tz.transition 1919, 3, :o3, 58128467, 24
-
1
tz.transition 1919, 10, :o2, 58133699, 24
-
1
tz.transition 1920, 2, :o3, 58136867, 24
-
1
tz.transition 1920, 10, :o2, 58142915, 24
-
1
tz.transition 1921, 3, :o3, 58146323, 24
-
1
tz.transition 1921, 10, :o2, 58151723, 24
-
1
tz.transition 1922, 3, :o3, 58155347, 24
-
1
tz.transition 1922, 10, :o2, 58160051, 24
-
1
tz.transition 1923, 5, :o3, 58165595, 24
-
1
tz.transition 1923, 10, :o2, 58168787, 24
-
1
tz.transition 1924, 3, :o3, 58172987, 24
-
1
tz.transition 1924, 10, :o2, 58177523, 24
-
1
tz.transition 1925, 4, :o3, 58181891, 24
-
1
tz.transition 1925, 10, :o2, 58186259, 24
-
1
tz.transition 1926, 4, :o3, 58190963, 24
-
1
tz.transition 1926, 10, :o2, 58194995, 24
-
1
tz.transition 1927, 4, :o3, 58199531, 24
-
1
tz.transition 1927, 10, :o2, 58203731, 24
-
1
tz.transition 1928, 4, :o3, 58208435, 24
-
1
tz.transition 1928, 10, :o2, 58212635, 24
-
1
tz.transition 1929, 4, :o3, 58217339, 24
-
1
tz.transition 1929, 10, :o2, 58221371, 24
-
1
tz.transition 1930, 4, :o3, 58225907, 24
-
1
tz.transition 1930, 10, :o2, 58230107, 24
-
1
tz.transition 1931, 4, :o3, 58234811, 24
-
1
tz.transition 1931, 10, :o2, 58238843, 24
-
1
tz.transition 1932, 4, :o3, 58243211, 24
-
1
tz.transition 1932, 10, :o2, 58247579, 24
-
1
tz.transition 1933, 3, :o3, 58251779, 24
-
1
tz.transition 1933, 10, :o2, 58256483, 24
-
1
tz.transition 1934, 4, :o3, 58260851, 24
-
1
tz.transition 1934, 10, :o2, 58265219, 24
-
1
tz.transition 1935, 3, :o3, 58269419, 24
-
1
tz.transition 1935, 10, :o2, 58273955, 24
-
1
tz.transition 1936, 4, :o3, 58278659, 24
-
1
tz.transition 1936, 10, :o2, 58282691, 24
-
1
tz.transition 1937, 4, :o3, 58287059, 24
-
1
tz.transition 1937, 10, :o2, 58291427, 24
-
1
tz.transition 1938, 3, :o3, 58295627, 24
-
1
tz.transition 1938, 10, :o2, 58300163, 24
-
1
tz.transition 1939, 4, :o3, 58304867, 24
-
1
tz.transition 1939, 11, :o2, 58310075, 24
-
1
tz.transition 1940, 2, :o3, 29156215, 12
-
1
tz.transition 1940, 6, :o4, 29157545, 12
-
1
tz.transition 1942, 11, :o5, 58335973, 24
-
1
tz.transition 1943, 3, :o4, 58339501, 24
-
1
tz.transition 1943, 10, :o5, 58344037, 24
-
1
tz.transition 1944, 4, :o4, 58348405, 24
-
1
tz.transition 1944, 8, :o6, 29175929, 12
-
1
tz.transition 1944, 10, :o3, 58352915, 24
-
1
tz.transition 1945, 4, :o6, 58357141, 24
-
1
tz.transition 1945, 9, :o5, 58361149, 24
-
1
tz.transition 1976, 3, :o4, 196819200
-
1
tz.transition 1976, 9, :o5, 212540400
-
1
tz.transition 1977, 4, :o4, 228877200
-
1
tz.transition 1977, 9, :o5, 243997200
-
1
tz.transition 1978, 4, :o4, 260326800
-
1
tz.transition 1978, 10, :o5, 276051600
-
1
tz.transition 1979, 4, :o4, 291776400
-
1
tz.transition 1979, 9, :o5, 307501200
-
1
tz.transition 1980, 4, :o4, 323830800
-
1
tz.transition 1980, 9, :o5, 338950800
-
1
tz.transition 1981, 3, :o4, 354675600
-
1
tz.transition 1981, 9, :o5, 370400400
-
1
tz.transition 1982, 3, :o4, 386125200
-
1
tz.transition 1982, 9, :o5, 401850000
-
1
tz.transition 1983, 3, :o4, 417574800
-
1
tz.transition 1983, 9, :o5, 433299600
-
1
tz.transition 1984, 3, :o4, 449024400
-
1
tz.transition 1984, 9, :o5, 465354000
-
1
tz.transition 1985, 3, :o4, 481078800
-
1
tz.transition 1985, 9, :o5, 496803600
-
1
tz.transition 1986, 3, :o4, 512528400
-
1
tz.transition 1986, 9, :o5, 528253200
-
1
tz.transition 1987, 3, :o4, 543978000
-
1
tz.transition 1987, 9, :o5, 559702800
-
1
tz.transition 1988, 3, :o4, 575427600
-
1
tz.transition 1988, 9, :o5, 591152400
-
1
tz.transition 1989, 3, :o4, 606877200
-
1
tz.transition 1989, 9, :o5, 622602000
-
1
tz.transition 1990, 3, :o4, 638326800
-
1
tz.transition 1990, 9, :o5, 654656400
-
1
tz.transition 1991, 3, :o4, 670381200
-
1
tz.transition 1991, 9, :o5, 686106000
-
1
tz.transition 1992, 3, :o4, 701830800
-
1
tz.transition 1992, 9, :o5, 717555600
-
1
tz.transition 1993, 3, :o4, 733280400
-
1
tz.transition 1993, 9, :o5, 749005200
-
1
tz.transition 1994, 3, :o4, 764730000
-
1
tz.transition 1994, 9, :o5, 780454800
-
1
tz.transition 1995, 3, :o4, 796179600
-
1
tz.transition 1995, 9, :o5, 811904400
-
1
tz.transition 1996, 3, :o4, 828234000
-
1
tz.transition 1996, 10, :o5, 846378000
-
1
tz.transition 1997, 3, :o4, 859683600
-
1
tz.transition 1997, 10, :o5, 877827600
-
1
tz.transition 1998, 3, :o4, 891133200
-
1
tz.transition 1998, 10, :o5, 909277200
-
1
tz.transition 1999, 3, :o4, 922582800
-
1
tz.transition 1999, 10, :o5, 941331600
-
1
tz.transition 2000, 3, :o4, 954032400
-
1
tz.transition 2000, 10, :o5, 972781200
-
1
tz.transition 2001, 3, :o4, 985482000
-
1
tz.transition 2001, 10, :o5, 1004230800
-
1
tz.transition 2002, 3, :o4, 1017536400
-
1
tz.transition 2002, 10, :o5, 1035680400
-
1
tz.transition 2003, 3, :o4, 1048986000
-
1
tz.transition 2003, 10, :o5, 1067130000
-
1
tz.transition 2004, 3, :o4, 1080435600
-
1
tz.transition 2004, 10, :o5, 1099184400
-
1
tz.transition 2005, 3, :o4, 1111885200
-
1
tz.transition 2005, 10, :o5, 1130634000
-
1
tz.transition 2006, 3, :o4, 1143334800
-
1
tz.transition 2006, 10, :o5, 1162083600
-
1
tz.transition 2007, 3, :o4, 1174784400
-
1
tz.transition 2007, 10, :o5, 1193533200
-
1
tz.transition 2008, 3, :o4, 1206838800
-
1
tz.transition 2008, 10, :o5, 1224982800
-
1
tz.transition 2009, 3, :o4, 1238288400
-
1
tz.transition 2009, 10, :o5, 1256432400
-
1
tz.transition 2010, 3, :o4, 1269738000
-
1
tz.transition 2010, 10, :o5, 1288486800
-
1
tz.transition 2011, 3, :o4, 1301187600
-
1
tz.transition 2011, 10, :o5, 1319936400
-
1
tz.transition 2012, 3, :o4, 1332637200
-
1
tz.transition 2012, 10, :o5, 1351386000
-
1
tz.transition 2013, 3, :o4, 1364691600
-
1
tz.transition 2013, 10, :o5, 1382835600
-
1
tz.transition 2014, 3, :o4, 1396141200
-
1
tz.transition 2014, 10, :o5, 1414285200
-
1
tz.transition 2015, 3, :o4, 1427590800
-
1
tz.transition 2015, 10, :o5, 1445734800
-
1
tz.transition 2016, 3, :o4, 1459040400
-
1
tz.transition 2016, 10, :o5, 1477789200
-
1
tz.transition 2017, 3, :o4, 1490490000
-
1
tz.transition 2017, 10, :o5, 1509238800
-
1
tz.transition 2018, 3, :o4, 1521939600
-
1
tz.transition 2018, 10, :o5, 1540688400
-
1
tz.transition 2019, 3, :o4, 1553994000
-
1
tz.transition 2019, 10, :o5, 1572138000
-
1
tz.transition 2020, 3, :o4, 1585443600
-
1
tz.transition 2020, 10, :o5, 1603587600
-
1
tz.transition 2021, 3, :o4, 1616893200
-
1
tz.transition 2021, 10, :o5, 1635642000
-
1
tz.transition 2022, 3, :o4, 1648342800
-
1
tz.transition 2022, 10, :o5, 1667091600
-
1
tz.transition 2023, 3, :o4, 1679792400
-
1
tz.transition 2023, 10, :o5, 1698541200
-
1
tz.transition 2024, 3, :o4, 1711846800
-
1
tz.transition 2024, 10, :o5, 1729990800
-
1
tz.transition 2025, 3, :o4, 1743296400
-
1
tz.transition 2025, 10, :o5, 1761440400
-
1
tz.transition 2026, 3, :o4, 1774746000
-
1
tz.transition 2026, 10, :o5, 1792890000
-
1
tz.transition 2027, 3, :o4, 1806195600
-
1
tz.transition 2027, 10, :o5, 1824944400
-
1
tz.transition 2028, 3, :o4, 1837645200
-
1
tz.transition 2028, 10, :o5, 1856394000
-
1
tz.transition 2029, 3, :o4, 1869094800
-
1
tz.transition 2029, 10, :o5, 1887843600
-
1
tz.transition 2030, 3, :o4, 1901149200
-
1
tz.transition 2030, 10, :o5, 1919293200
-
1
tz.transition 2031, 3, :o4, 1932598800
-
1
tz.transition 2031, 10, :o5, 1950742800
-
1
tz.transition 2032, 3, :o4, 1964048400
-
1
tz.transition 2032, 10, :o5, 1982797200
-
1
tz.transition 2033, 3, :o4, 1995498000
-
1
tz.transition 2033, 10, :o5, 2014246800
-
1
tz.transition 2034, 3, :o4, 2026947600
-
1
tz.transition 2034, 10, :o5, 2045696400
-
1
tz.transition 2035, 3, :o4, 2058397200
-
1
tz.transition 2035, 10, :o5, 2077146000
-
1
tz.transition 2036, 3, :o4, 2090451600
-
1
tz.transition 2036, 10, :o5, 2108595600
-
1
tz.transition 2037, 3, :o4, 2121901200
-
1
tz.transition 2037, 10, :o5, 2140045200
-
1
tz.transition 2038, 3, :o4, 59172253, 24
-
1
tz.transition 2038, 10, :o5, 59177461, 24
-
1
tz.transition 2039, 3, :o4, 59180989, 24
-
1
tz.transition 2039, 10, :o5, 59186197, 24
-
1
tz.transition 2040, 3, :o4, 59189725, 24
-
1
tz.transition 2040, 10, :o5, 59194933, 24
-
1
tz.transition 2041, 3, :o4, 59198629, 24
-
1
tz.transition 2041, 10, :o5, 59203669, 24
-
1
tz.transition 2042, 3, :o4, 59207365, 24
-
1
tz.transition 2042, 10, :o5, 59212405, 24
-
1
tz.transition 2043, 3, :o4, 59216101, 24
-
1
tz.transition 2043, 10, :o5, 59221141, 24
-
1
tz.transition 2044, 3, :o4, 59224837, 24
-
1
tz.transition 2044, 10, :o5, 59230045, 24
-
1
tz.transition 2045, 3, :o4, 59233573, 24
-
1
tz.transition 2045, 10, :o5, 59238781, 24
-
1
tz.transition 2046, 3, :o4, 59242309, 24
-
1
tz.transition 2046, 10, :o5, 59247517, 24
-
1
tz.transition 2047, 3, :o4, 59251213, 24
-
1
tz.transition 2047, 10, :o5, 59256253, 24
-
1
tz.transition 2048, 3, :o4, 59259949, 24
-
1
tz.transition 2048, 10, :o5, 59264989, 24
-
1
tz.transition 2049, 3, :o4, 59268685, 24
-
1
tz.transition 2049, 10, :o5, 59273893, 24
-
1
tz.transition 2050, 3, :o4, 59277421, 24
-
1
tz.transition 2050, 10, :o5, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Prague
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Prague' do |tz|
-
1
tz.offset :o0, 3464, 0, :LMT
-
1
tz.offset :o1, 3464, 0, :PMT
-
1
tz.offset :o2, 3600, 0, :CET
-
1
tz.offset :o3, 3600, 3600, :CEST
-
-
1
tz.transition 1849, 12, :o1, 25884991367, 10800
-
1
tz.transition 1891, 9, :o2, 26049669767, 10800
-
1
tz.transition 1916, 4, :o3, 29051813, 12
-
1
tz.transition 1916, 9, :o2, 58107299, 24
-
1
tz.transition 1917, 4, :o3, 58112029, 24
-
1
tz.transition 1917, 9, :o2, 58115725, 24
-
1
tz.transition 1918, 4, :o3, 58120765, 24
-
1
tz.transition 1918, 9, :o2, 58124461, 24
-
1
tz.transition 1940, 4, :o3, 58313293, 24
-
1
tz.transition 1942, 11, :o2, 58335973, 24
-
1
tz.transition 1943, 3, :o3, 58339501, 24
-
1
tz.transition 1943, 10, :o2, 58344037, 24
-
1
tz.transition 1944, 4, :o3, 58348405, 24
-
1
tz.transition 1944, 9, :o2, 58352413, 24
-
1
tz.transition 1945, 4, :o3, 58357285, 24
-
1
tz.transition 1945, 11, :o2, 58362661, 24
-
1
tz.transition 1946, 5, :o3, 58366717, 24
-
1
tz.transition 1946, 10, :o2, 58370389, 24
-
1
tz.transition 1947, 4, :o3, 58375093, 24
-
1
tz.transition 1947, 10, :o2, 58379125, 24
-
1
tz.transition 1948, 4, :o3, 58383829, 24
-
1
tz.transition 1948, 10, :o2, 58387861, 24
-
1
tz.transition 1949, 4, :o3, 58392373, 24
-
1
tz.transition 1949, 10, :o2, 58396597, 24
-
1
tz.transition 1979, 4, :o3, 291776400
-
1
tz.transition 1979, 9, :o2, 307501200
-
1
tz.transition 1980, 4, :o3, 323830800
-
1
tz.transition 1980, 9, :o2, 338950800
-
1
tz.transition 1981, 3, :o3, 354675600
-
1
tz.transition 1981, 9, :o2, 370400400
-
1
tz.transition 1982, 3, :o3, 386125200
-
1
tz.transition 1982, 9, :o2, 401850000
-
1
tz.transition 1983, 3, :o3, 417574800
-
1
tz.transition 1983, 9, :o2, 433299600
-
1
tz.transition 1984, 3, :o3, 449024400
-
1
tz.transition 1984, 9, :o2, 465354000
-
1
tz.transition 1985, 3, :o3, 481078800
-
1
tz.transition 1985, 9, :o2, 496803600
-
1
tz.transition 1986, 3, :o3, 512528400
-
1
tz.transition 1986, 9, :o2, 528253200
-
1
tz.transition 1987, 3, :o3, 543978000
-
1
tz.transition 1987, 9, :o2, 559702800
-
1
tz.transition 1988, 3, :o3, 575427600
-
1
tz.transition 1988, 9, :o2, 591152400
-
1
tz.transition 1989, 3, :o3, 606877200
-
1
tz.transition 1989, 9, :o2, 622602000
-
1
tz.transition 1990, 3, :o3, 638326800
-
1
tz.transition 1990, 9, :o2, 654656400
-
1
tz.transition 1991, 3, :o3, 670381200
-
1
tz.transition 1991, 9, :o2, 686106000
-
1
tz.transition 1992, 3, :o3, 701830800
-
1
tz.transition 1992, 9, :o2, 717555600
-
1
tz.transition 1993, 3, :o3, 733280400
-
1
tz.transition 1993, 9, :o2, 749005200
-
1
tz.transition 1994, 3, :o3, 764730000
-
1
tz.transition 1994, 9, :o2, 780454800
-
1
tz.transition 1995, 3, :o3, 796179600
-
1
tz.transition 1995, 9, :o2, 811904400
-
1
tz.transition 1996, 3, :o3, 828234000
-
1
tz.transition 1996, 10, :o2, 846378000
-
1
tz.transition 1997, 3, :o3, 859683600
-
1
tz.transition 1997, 10, :o2, 877827600
-
1
tz.transition 1998, 3, :o3, 891133200
-
1
tz.transition 1998, 10, :o2, 909277200
-
1
tz.transition 1999, 3, :o3, 922582800
-
1
tz.transition 1999, 10, :o2, 941331600
-
1
tz.transition 2000, 3, :o3, 954032400
-
1
tz.transition 2000, 10, :o2, 972781200
-
1
tz.transition 2001, 3, :o3, 985482000
-
1
tz.transition 2001, 10, :o2, 1004230800
-
1
tz.transition 2002, 3, :o3, 1017536400
-
1
tz.transition 2002, 10, :o2, 1035680400
-
1
tz.transition 2003, 3, :o3, 1048986000
-
1
tz.transition 2003, 10, :o2, 1067130000
-
1
tz.transition 2004, 3, :o3, 1080435600
-
1
tz.transition 2004, 10, :o2, 1099184400
-
1
tz.transition 2005, 3, :o3, 1111885200
-
1
tz.transition 2005, 10, :o2, 1130634000
-
1
tz.transition 2006, 3, :o3, 1143334800
-
1
tz.transition 2006, 10, :o2, 1162083600
-
1
tz.transition 2007, 3, :o3, 1174784400
-
1
tz.transition 2007, 10, :o2, 1193533200
-
1
tz.transition 2008, 3, :o3, 1206838800
-
1
tz.transition 2008, 10, :o2, 1224982800
-
1
tz.transition 2009, 3, :o3, 1238288400
-
1
tz.transition 2009, 10, :o2, 1256432400
-
1
tz.transition 2010, 3, :o3, 1269738000
-
1
tz.transition 2010, 10, :o2, 1288486800
-
1
tz.transition 2011, 3, :o3, 1301187600
-
1
tz.transition 2011, 10, :o2, 1319936400
-
1
tz.transition 2012, 3, :o3, 1332637200
-
1
tz.transition 2012, 10, :o2, 1351386000
-
1
tz.transition 2013, 3, :o3, 1364691600
-
1
tz.transition 2013, 10, :o2, 1382835600
-
1
tz.transition 2014, 3, :o3, 1396141200
-
1
tz.transition 2014, 10, :o2, 1414285200
-
1
tz.transition 2015, 3, :o3, 1427590800
-
1
tz.transition 2015, 10, :o2, 1445734800
-
1
tz.transition 2016, 3, :o3, 1459040400
-
1
tz.transition 2016, 10, :o2, 1477789200
-
1
tz.transition 2017, 3, :o3, 1490490000
-
1
tz.transition 2017, 10, :o2, 1509238800
-
1
tz.transition 2018, 3, :o3, 1521939600
-
1
tz.transition 2018, 10, :o2, 1540688400
-
1
tz.transition 2019, 3, :o3, 1553994000
-
1
tz.transition 2019, 10, :o2, 1572138000
-
1
tz.transition 2020, 3, :o3, 1585443600
-
1
tz.transition 2020, 10, :o2, 1603587600
-
1
tz.transition 2021, 3, :o3, 1616893200
-
1
tz.transition 2021, 10, :o2, 1635642000
-
1
tz.transition 2022, 3, :o3, 1648342800
-
1
tz.transition 2022, 10, :o2, 1667091600
-
1
tz.transition 2023, 3, :o3, 1679792400
-
1
tz.transition 2023, 10, :o2, 1698541200
-
1
tz.transition 2024, 3, :o3, 1711846800
-
1
tz.transition 2024, 10, :o2, 1729990800
-
1
tz.transition 2025, 3, :o3, 1743296400
-
1
tz.transition 2025, 10, :o2, 1761440400
-
1
tz.transition 2026, 3, :o3, 1774746000
-
1
tz.transition 2026, 10, :o2, 1792890000
-
1
tz.transition 2027, 3, :o3, 1806195600
-
1
tz.transition 2027, 10, :o2, 1824944400
-
1
tz.transition 2028, 3, :o3, 1837645200
-
1
tz.transition 2028, 10, :o2, 1856394000
-
1
tz.transition 2029, 3, :o3, 1869094800
-
1
tz.transition 2029, 10, :o2, 1887843600
-
1
tz.transition 2030, 3, :o3, 1901149200
-
1
tz.transition 2030, 10, :o2, 1919293200
-
1
tz.transition 2031, 3, :o3, 1932598800
-
1
tz.transition 2031, 10, :o2, 1950742800
-
1
tz.transition 2032, 3, :o3, 1964048400
-
1
tz.transition 2032, 10, :o2, 1982797200
-
1
tz.transition 2033, 3, :o3, 1995498000
-
1
tz.transition 2033, 10, :o2, 2014246800
-
1
tz.transition 2034, 3, :o3, 2026947600
-
1
tz.transition 2034, 10, :o2, 2045696400
-
1
tz.transition 2035, 3, :o3, 2058397200
-
1
tz.transition 2035, 10, :o2, 2077146000
-
1
tz.transition 2036, 3, :o3, 2090451600
-
1
tz.transition 2036, 10, :o2, 2108595600
-
1
tz.transition 2037, 3, :o3, 2121901200
-
1
tz.transition 2037, 10, :o2, 2140045200
-
1
tz.transition 2038, 3, :o3, 59172253, 24
-
1
tz.transition 2038, 10, :o2, 59177461, 24
-
1
tz.transition 2039, 3, :o3, 59180989, 24
-
1
tz.transition 2039, 10, :o2, 59186197, 24
-
1
tz.transition 2040, 3, :o3, 59189725, 24
-
1
tz.transition 2040, 10, :o2, 59194933, 24
-
1
tz.transition 2041, 3, :o3, 59198629, 24
-
1
tz.transition 2041, 10, :o2, 59203669, 24
-
1
tz.transition 2042, 3, :o3, 59207365, 24
-
1
tz.transition 2042, 10, :o2, 59212405, 24
-
1
tz.transition 2043, 3, :o3, 59216101, 24
-
1
tz.transition 2043, 10, :o2, 59221141, 24
-
1
tz.transition 2044, 3, :o3, 59224837, 24
-
1
tz.transition 2044, 10, :o2, 59230045, 24
-
1
tz.transition 2045, 3, :o3, 59233573, 24
-
1
tz.transition 2045, 10, :o2, 59238781, 24
-
1
tz.transition 2046, 3, :o3, 59242309, 24
-
1
tz.transition 2046, 10, :o2, 59247517, 24
-
1
tz.transition 2047, 3, :o3, 59251213, 24
-
1
tz.transition 2047, 10, :o2, 59256253, 24
-
1
tz.transition 2048, 3, :o3, 59259949, 24
-
1
tz.transition 2048, 10, :o2, 59264989, 24
-
1
tz.transition 2049, 3, :o3, 59268685, 24
-
1
tz.transition 2049, 10, :o2, 59273893, 24
-
1
tz.transition 2050, 3, :o3, 59277421, 24
-
1
tz.transition 2050, 10, :o2, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Riga
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Riga' do |tz|
-
1
tz.offset :o0, 5784, 0, :LMT
-
1
tz.offset :o1, 5784, 0, :RMT
-
1
tz.offset :o2, 5784, 3600, :LST
-
1
tz.offset :o3, 7200, 0, :EET
-
1
tz.offset :o4, 10800, 0, :MSK
-
1
tz.offset :o5, 3600, 3600, :CEST
-
1
tz.offset :o6, 3600, 0, :CET
-
1
tz.offset :o7, 10800, 3600, :MSD
-
1
tz.offset :o8, 7200, 3600, :EEST
-
-
1
tz.transition 1879, 12, :o1, 8667775559, 3600
-
1
tz.transition 1918, 4, :o2, 8718114659, 3600
-
1
tz.transition 1918, 9, :o1, 8718669059, 3600
-
1
tz.transition 1919, 4, :o2, 8719378259, 3600
-
1
tz.transition 1919, 5, :o1, 8719561859, 3600
-
1
tz.transition 1926, 5, :o3, 8728727159, 3600
-
1
tz.transition 1940, 8, :o4, 29158157, 12
-
1
tz.transition 1941, 6, :o5, 19441411, 8
-
1
tz.transition 1942, 11, :o6, 58335973, 24
-
1
tz.transition 1943, 3, :o5, 58339501, 24
-
1
tz.transition 1943, 10, :o6, 58344037, 24
-
1
tz.transition 1944, 4, :o5, 58348405, 24
-
1
tz.transition 1944, 10, :o6, 58352773, 24
-
1
tz.transition 1944, 10, :o4, 58353035, 24
-
1
tz.transition 1981, 3, :o7, 354920400
-
1
tz.transition 1981, 9, :o4, 370728000
-
1
tz.transition 1982, 3, :o7, 386456400
-
1
tz.transition 1982, 9, :o4, 402264000
-
1
tz.transition 1983, 3, :o7, 417992400
-
1
tz.transition 1983, 9, :o4, 433800000
-
1
tz.transition 1984, 3, :o7, 449614800
-
1
tz.transition 1984, 9, :o4, 465346800
-
1
tz.transition 1985, 3, :o7, 481071600
-
1
tz.transition 1985, 9, :o4, 496796400
-
1
tz.transition 1986, 3, :o7, 512521200
-
1
tz.transition 1986, 9, :o4, 528246000
-
1
tz.transition 1987, 3, :o7, 543970800
-
1
tz.transition 1987, 9, :o4, 559695600
-
1
tz.transition 1988, 3, :o7, 575420400
-
1
tz.transition 1988, 9, :o4, 591145200
-
1
tz.transition 1989, 3, :o8, 606870000
-
1
tz.transition 1989, 9, :o3, 622598400
-
1
tz.transition 1990, 3, :o8, 638323200
-
1
tz.transition 1990, 9, :o3, 654652800
-
1
tz.transition 1991, 3, :o8, 670377600
-
1
tz.transition 1991, 9, :o3, 686102400
-
1
tz.transition 1992, 3, :o8, 701827200
-
1
tz.transition 1992, 9, :o3, 717552000
-
1
tz.transition 1993, 3, :o8, 733276800
-
1
tz.transition 1993, 9, :o3, 749001600
-
1
tz.transition 1994, 3, :o8, 764726400
-
1
tz.transition 1994, 9, :o3, 780451200
-
1
tz.transition 1995, 3, :o8, 796176000
-
1
tz.transition 1995, 9, :o3, 811900800
-
1
tz.transition 1996, 3, :o8, 828230400
-
1
tz.transition 1996, 9, :o3, 843955200
-
1
tz.transition 1997, 3, :o8, 859683600
-
1
tz.transition 1997, 10, :o3, 877827600
-
1
tz.transition 1998, 3, :o8, 891133200
-
1
tz.transition 1998, 10, :o3, 909277200
-
1
tz.transition 1999, 3, :o8, 922582800
-
1
tz.transition 1999, 10, :o3, 941331600
-
1
tz.transition 2001, 3, :o8, 985482000
-
1
tz.transition 2001, 10, :o3, 1004230800
-
1
tz.transition 2002, 3, :o8, 1017536400
-
1
tz.transition 2002, 10, :o3, 1035680400
-
1
tz.transition 2003, 3, :o8, 1048986000
-
1
tz.transition 2003, 10, :o3, 1067130000
-
1
tz.transition 2004, 3, :o8, 1080435600
-
1
tz.transition 2004, 10, :o3, 1099184400
-
1
tz.transition 2005, 3, :o8, 1111885200
-
1
tz.transition 2005, 10, :o3, 1130634000
-
1
tz.transition 2006, 3, :o8, 1143334800
-
1
tz.transition 2006, 10, :o3, 1162083600
-
1
tz.transition 2007, 3, :o8, 1174784400
-
1
tz.transition 2007, 10, :o3, 1193533200
-
1
tz.transition 2008, 3, :o8, 1206838800
-
1
tz.transition 2008, 10, :o3, 1224982800
-
1
tz.transition 2009, 3, :o8, 1238288400
-
1
tz.transition 2009, 10, :o3, 1256432400
-
1
tz.transition 2010, 3, :o8, 1269738000
-
1
tz.transition 2010, 10, :o3, 1288486800
-
1
tz.transition 2011, 3, :o8, 1301187600
-
1
tz.transition 2011, 10, :o3, 1319936400
-
1
tz.transition 2012, 3, :o8, 1332637200
-
1
tz.transition 2012, 10, :o3, 1351386000
-
1
tz.transition 2013, 3, :o8, 1364691600
-
1
tz.transition 2013, 10, :o3, 1382835600
-
1
tz.transition 2014, 3, :o8, 1396141200
-
1
tz.transition 2014, 10, :o3, 1414285200
-
1
tz.transition 2015, 3, :o8, 1427590800
-
1
tz.transition 2015, 10, :o3, 1445734800
-
1
tz.transition 2016, 3, :o8, 1459040400
-
1
tz.transition 2016, 10, :o3, 1477789200
-
1
tz.transition 2017, 3, :o8, 1490490000
-
1
tz.transition 2017, 10, :o3, 1509238800
-
1
tz.transition 2018, 3, :o8, 1521939600
-
1
tz.transition 2018, 10, :o3, 1540688400
-
1
tz.transition 2019, 3, :o8, 1553994000
-
1
tz.transition 2019, 10, :o3, 1572138000
-
1
tz.transition 2020, 3, :o8, 1585443600
-
1
tz.transition 2020, 10, :o3, 1603587600
-
1
tz.transition 2021, 3, :o8, 1616893200
-
1
tz.transition 2021, 10, :o3, 1635642000
-
1
tz.transition 2022, 3, :o8, 1648342800
-
1
tz.transition 2022, 10, :o3, 1667091600
-
1
tz.transition 2023, 3, :o8, 1679792400
-
1
tz.transition 2023, 10, :o3, 1698541200
-
1
tz.transition 2024, 3, :o8, 1711846800
-
1
tz.transition 2024, 10, :o3, 1729990800
-
1
tz.transition 2025, 3, :o8, 1743296400
-
1
tz.transition 2025, 10, :o3, 1761440400
-
1
tz.transition 2026, 3, :o8, 1774746000
-
1
tz.transition 2026, 10, :o3, 1792890000
-
1
tz.transition 2027, 3, :o8, 1806195600
-
1
tz.transition 2027, 10, :o3, 1824944400
-
1
tz.transition 2028, 3, :o8, 1837645200
-
1
tz.transition 2028, 10, :o3, 1856394000
-
1
tz.transition 2029, 3, :o8, 1869094800
-
1
tz.transition 2029, 10, :o3, 1887843600
-
1
tz.transition 2030, 3, :o8, 1901149200
-
1
tz.transition 2030, 10, :o3, 1919293200
-
1
tz.transition 2031, 3, :o8, 1932598800
-
1
tz.transition 2031, 10, :o3, 1950742800
-
1
tz.transition 2032, 3, :o8, 1964048400
-
1
tz.transition 2032, 10, :o3, 1982797200
-
1
tz.transition 2033, 3, :o8, 1995498000
-
1
tz.transition 2033, 10, :o3, 2014246800
-
1
tz.transition 2034, 3, :o8, 2026947600
-
1
tz.transition 2034, 10, :o3, 2045696400
-
1
tz.transition 2035, 3, :o8, 2058397200
-
1
tz.transition 2035, 10, :o3, 2077146000
-
1
tz.transition 2036, 3, :o8, 2090451600
-
1
tz.transition 2036, 10, :o3, 2108595600
-
1
tz.transition 2037, 3, :o8, 2121901200
-
1
tz.transition 2037, 10, :o3, 2140045200
-
1
tz.transition 2038, 3, :o8, 59172253, 24
-
1
tz.transition 2038, 10, :o3, 59177461, 24
-
1
tz.transition 2039, 3, :o8, 59180989, 24
-
1
tz.transition 2039, 10, :o3, 59186197, 24
-
1
tz.transition 2040, 3, :o8, 59189725, 24
-
1
tz.transition 2040, 10, :o3, 59194933, 24
-
1
tz.transition 2041, 3, :o8, 59198629, 24
-
1
tz.transition 2041, 10, :o3, 59203669, 24
-
1
tz.transition 2042, 3, :o8, 59207365, 24
-
1
tz.transition 2042, 10, :o3, 59212405, 24
-
1
tz.transition 2043, 3, :o8, 59216101, 24
-
1
tz.transition 2043, 10, :o3, 59221141, 24
-
1
tz.transition 2044, 3, :o8, 59224837, 24
-
1
tz.transition 2044, 10, :o3, 59230045, 24
-
1
tz.transition 2045, 3, :o8, 59233573, 24
-
1
tz.transition 2045, 10, :o3, 59238781, 24
-
1
tz.transition 2046, 3, :o8, 59242309, 24
-
1
tz.transition 2046, 10, :o3, 59247517, 24
-
1
tz.transition 2047, 3, :o8, 59251213, 24
-
1
tz.transition 2047, 10, :o3, 59256253, 24
-
1
tz.transition 2048, 3, :o8, 59259949, 24
-
1
tz.transition 2048, 10, :o3, 59264989, 24
-
1
tz.transition 2049, 3, :o8, 59268685, 24
-
1
tz.transition 2049, 10, :o3, 59273893, 24
-
1
tz.transition 2050, 3, :o8, 59277421, 24
-
1
tz.transition 2050, 10, :o3, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Rome
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Rome' do |tz|
-
1
tz.offset :o0, 2996, 0, :LMT
-
1
tz.offset :o1, 2996, 0, :RMT
-
1
tz.offset :o2, 3600, 0, :CET
-
1
tz.offset :o3, 3600, 3600, :CEST
-
-
1
tz.transition 1866, 9, :o1, 51901915651, 21600
-
1
tz.transition 1893, 10, :o2, 52115798851, 21600
-
1
tz.transition 1916, 6, :o3, 58104419, 24
-
1
tz.transition 1916, 9, :o2, 58107299, 24
-
1
tz.transition 1917, 3, :o3, 58111667, 24
-
1
tz.transition 1917, 9, :o2, 58116035, 24
-
1
tz.transition 1918, 3, :o3, 58119899, 24
-
1
tz.transition 1918, 10, :o2, 58124939, 24
-
1
tz.transition 1919, 3, :o3, 58128467, 24
-
1
tz.transition 1919, 10, :o2, 58133675, 24
-
1
tz.transition 1920, 3, :o3, 58137707, 24
-
1
tz.transition 1920, 9, :o2, 58142075, 24
-
1
tz.transition 1940, 6, :o3, 58315091, 24
-
1
tz.transition 1942, 11, :o2, 58335973, 24
-
1
tz.transition 1943, 3, :o3, 58339501, 24
-
1
tz.transition 1943, 10, :o2, 58344037, 24
-
1
tz.transition 1944, 4, :o3, 58348405, 24
-
1
tz.transition 1944, 9, :o2, 58352411, 24
-
1
tz.transition 1945, 4, :o3, 58357141, 24
-
1
tz.transition 1945, 9, :o2, 58361123, 24
-
1
tz.transition 1946, 3, :o3, 58365517, 24
-
1
tz.transition 1946, 10, :o2, 58370389, 24
-
1
tz.transition 1947, 3, :o3, 58374251, 24
-
1
tz.transition 1947, 10, :o2, 58379123, 24
-
1
tz.transition 1948, 2, :o3, 58382653, 24
-
1
tz.transition 1948, 10, :o2, 58387861, 24
-
1
tz.transition 1966, 5, :o3, 58542419, 24
-
1
tz.transition 1966, 9, :o2, 29272721, 12
-
1
tz.transition 1967, 5, :o3, 58551323, 24
-
1
tz.transition 1967, 9, :o2, 29277089, 12
-
1
tz.transition 1968, 5, :o3, 58560059, 24
-
1
tz.transition 1968, 9, :o2, 29281457, 12
-
1
tz.transition 1969, 5, :o3, 58568963, 24
-
1
tz.transition 1969, 9, :o2, 29285909, 12
-
1
tz.transition 1970, 5, :o3, 12956400
-
1
tz.transition 1970, 9, :o2, 23234400
-
1
tz.transition 1971, 5, :o3, 43801200
-
1
tz.transition 1971, 9, :o2, 54687600
-
1
tz.transition 1972, 5, :o3, 75855600
-
1
tz.transition 1972, 9, :o2, 86738400
-
1
tz.transition 1973, 6, :o3, 107910000
-
1
tz.transition 1973, 9, :o2, 118188000
-
1
tz.transition 1974, 5, :o3, 138754800
-
1
tz.transition 1974, 9, :o2, 149637600
-
1
tz.transition 1975, 5, :o3, 170809200
-
1
tz.transition 1975, 9, :o2, 181090800
-
1
tz.transition 1976, 5, :o3, 202258800
-
1
tz.transition 1976, 9, :o2, 212540400
-
1
tz.transition 1977, 5, :o3, 233103600
-
1
tz.transition 1977, 9, :o2, 243990000
-
1
tz.transition 1978, 5, :o3, 265158000
-
1
tz.transition 1978, 9, :o2, 276044400
-
1
tz.transition 1979, 5, :o3, 296607600
-
1
tz.transition 1979, 9, :o2, 307494000
-
1
tz.transition 1980, 4, :o3, 323830800
-
1
tz.transition 1980, 9, :o2, 338950800
-
1
tz.transition 1981, 3, :o3, 354675600
-
1
tz.transition 1981, 9, :o2, 370400400
-
1
tz.transition 1982, 3, :o3, 386125200
-
1
tz.transition 1982, 9, :o2, 401850000
-
1
tz.transition 1983, 3, :o3, 417574800
-
1
tz.transition 1983, 9, :o2, 433299600
-
1
tz.transition 1984, 3, :o3, 449024400
-
1
tz.transition 1984, 9, :o2, 465354000
-
1
tz.transition 1985, 3, :o3, 481078800
-
1
tz.transition 1985, 9, :o2, 496803600
-
1
tz.transition 1986, 3, :o3, 512528400
-
1
tz.transition 1986, 9, :o2, 528253200
-
1
tz.transition 1987, 3, :o3, 543978000
-
1
tz.transition 1987, 9, :o2, 559702800
-
1
tz.transition 1988, 3, :o3, 575427600
-
1
tz.transition 1988, 9, :o2, 591152400
-
1
tz.transition 1989, 3, :o3, 606877200
-
1
tz.transition 1989, 9, :o2, 622602000
-
1
tz.transition 1990, 3, :o3, 638326800
-
1
tz.transition 1990, 9, :o2, 654656400
-
1
tz.transition 1991, 3, :o3, 670381200
-
1
tz.transition 1991, 9, :o2, 686106000
-
1
tz.transition 1992, 3, :o3, 701830800
-
1
tz.transition 1992, 9, :o2, 717555600
-
1
tz.transition 1993, 3, :o3, 733280400
-
1
tz.transition 1993, 9, :o2, 749005200
-
1
tz.transition 1994, 3, :o3, 764730000
-
1
tz.transition 1994, 9, :o2, 780454800
-
1
tz.transition 1995, 3, :o3, 796179600
-
1
tz.transition 1995, 9, :o2, 811904400
-
1
tz.transition 1996, 3, :o3, 828234000
-
1
tz.transition 1996, 10, :o2, 846378000
-
1
tz.transition 1997, 3, :o3, 859683600
-
1
tz.transition 1997, 10, :o2, 877827600
-
1
tz.transition 1998, 3, :o3, 891133200
-
1
tz.transition 1998, 10, :o2, 909277200
-
1
tz.transition 1999, 3, :o3, 922582800
-
1
tz.transition 1999, 10, :o2, 941331600
-
1
tz.transition 2000, 3, :o3, 954032400
-
1
tz.transition 2000, 10, :o2, 972781200
-
1
tz.transition 2001, 3, :o3, 985482000
-
1
tz.transition 2001, 10, :o2, 1004230800
-
1
tz.transition 2002, 3, :o3, 1017536400
-
1
tz.transition 2002, 10, :o2, 1035680400
-
1
tz.transition 2003, 3, :o3, 1048986000
-
1
tz.transition 2003, 10, :o2, 1067130000
-
1
tz.transition 2004, 3, :o3, 1080435600
-
1
tz.transition 2004, 10, :o2, 1099184400
-
1
tz.transition 2005, 3, :o3, 1111885200
-
1
tz.transition 2005, 10, :o2, 1130634000
-
1
tz.transition 2006, 3, :o3, 1143334800
-
1
tz.transition 2006, 10, :o2, 1162083600
-
1
tz.transition 2007, 3, :o3, 1174784400
-
1
tz.transition 2007, 10, :o2, 1193533200
-
1
tz.transition 2008, 3, :o3, 1206838800
-
1
tz.transition 2008, 10, :o2, 1224982800
-
1
tz.transition 2009, 3, :o3, 1238288400
-
1
tz.transition 2009, 10, :o2, 1256432400
-
1
tz.transition 2010, 3, :o3, 1269738000
-
1
tz.transition 2010, 10, :o2, 1288486800
-
1
tz.transition 2011, 3, :o3, 1301187600
-
1
tz.transition 2011, 10, :o2, 1319936400
-
1
tz.transition 2012, 3, :o3, 1332637200
-
1
tz.transition 2012, 10, :o2, 1351386000
-
1
tz.transition 2013, 3, :o3, 1364691600
-
1
tz.transition 2013, 10, :o2, 1382835600
-
1
tz.transition 2014, 3, :o3, 1396141200
-
1
tz.transition 2014, 10, :o2, 1414285200
-
1
tz.transition 2015, 3, :o3, 1427590800
-
1
tz.transition 2015, 10, :o2, 1445734800
-
1
tz.transition 2016, 3, :o3, 1459040400
-
1
tz.transition 2016, 10, :o2, 1477789200
-
1
tz.transition 2017, 3, :o3, 1490490000
-
1
tz.transition 2017, 10, :o2, 1509238800
-
1
tz.transition 2018, 3, :o3, 1521939600
-
1
tz.transition 2018, 10, :o2, 1540688400
-
1
tz.transition 2019, 3, :o3, 1553994000
-
1
tz.transition 2019, 10, :o2, 1572138000
-
1
tz.transition 2020, 3, :o3, 1585443600
-
1
tz.transition 2020, 10, :o2, 1603587600
-
1
tz.transition 2021, 3, :o3, 1616893200
-
1
tz.transition 2021, 10, :o2, 1635642000
-
1
tz.transition 2022, 3, :o3, 1648342800
-
1
tz.transition 2022, 10, :o2, 1667091600
-
1
tz.transition 2023, 3, :o3, 1679792400
-
1
tz.transition 2023, 10, :o2, 1698541200
-
1
tz.transition 2024, 3, :o3, 1711846800
-
1
tz.transition 2024, 10, :o2, 1729990800
-
1
tz.transition 2025, 3, :o3, 1743296400
-
1
tz.transition 2025, 10, :o2, 1761440400
-
1
tz.transition 2026, 3, :o3, 1774746000
-
1
tz.transition 2026, 10, :o2, 1792890000
-
1
tz.transition 2027, 3, :o3, 1806195600
-
1
tz.transition 2027, 10, :o2, 1824944400
-
1
tz.transition 2028, 3, :o3, 1837645200
-
1
tz.transition 2028, 10, :o2, 1856394000
-
1
tz.transition 2029, 3, :o3, 1869094800
-
1
tz.transition 2029, 10, :o2, 1887843600
-
1
tz.transition 2030, 3, :o3, 1901149200
-
1
tz.transition 2030, 10, :o2, 1919293200
-
1
tz.transition 2031, 3, :o3, 1932598800
-
1
tz.transition 2031, 10, :o2, 1950742800
-
1
tz.transition 2032, 3, :o3, 1964048400
-
1
tz.transition 2032, 10, :o2, 1982797200
-
1
tz.transition 2033, 3, :o3, 1995498000
-
1
tz.transition 2033, 10, :o2, 2014246800
-
1
tz.transition 2034, 3, :o3, 2026947600
-
1
tz.transition 2034, 10, :o2, 2045696400
-
1
tz.transition 2035, 3, :o3, 2058397200
-
1
tz.transition 2035, 10, :o2, 2077146000
-
1
tz.transition 2036, 3, :o3, 2090451600
-
1
tz.transition 2036, 10, :o2, 2108595600
-
1
tz.transition 2037, 3, :o3, 2121901200
-
1
tz.transition 2037, 10, :o2, 2140045200
-
1
tz.transition 2038, 3, :o3, 59172253, 24
-
1
tz.transition 2038, 10, :o2, 59177461, 24
-
1
tz.transition 2039, 3, :o3, 59180989, 24
-
1
tz.transition 2039, 10, :o2, 59186197, 24
-
1
tz.transition 2040, 3, :o3, 59189725, 24
-
1
tz.transition 2040, 10, :o2, 59194933, 24
-
1
tz.transition 2041, 3, :o3, 59198629, 24
-
1
tz.transition 2041, 10, :o2, 59203669, 24
-
1
tz.transition 2042, 3, :o3, 59207365, 24
-
1
tz.transition 2042, 10, :o2, 59212405, 24
-
1
tz.transition 2043, 3, :o3, 59216101, 24
-
1
tz.transition 2043, 10, :o2, 59221141, 24
-
1
tz.transition 2044, 3, :o3, 59224837, 24
-
1
tz.transition 2044, 10, :o2, 59230045, 24
-
1
tz.transition 2045, 3, :o3, 59233573, 24
-
1
tz.transition 2045, 10, :o2, 59238781, 24
-
1
tz.transition 2046, 3, :o3, 59242309, 24
-
1
tz.transition 2046, 10, :o2, 59247517, 24
-
1
tz.transition 2047, 3, :o3, 59251213, 24
-
1
tz.transition 2047, 10, :o2, 59256253, 24
-
1
tz.transition 2048, 3, :o3, 59259949, 24
-
1
tz.transition 2048, 10, :o2, 59264989, 24
-
1
tz.transition 2049, 3, :o3, 59268685, 24
-
1
tz.transition 2049, 10, :o2, 59273893, 24
-
1
tz.transition 2050, 3, :o3, 59277421, 24
-
1
tz.transition 2050, 10, :o2, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Sarajevo
-
1
include TimezoneDefinition
-
-
1
linked_timezone 'Europe/Sarajevo', 'Europe/Belgrade'
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Skopje
-
1
include TimezoneDefinition
-
-
1
linked_timezone 'Europe/Skopje', 'Europe/Belgrade'
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Sofia
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Sofia' do |tz|
-
1
tz.offset :o0, 5596, 0, :LMT
-
1
tz.offset :o1, 7016, 0, :IMT
-
1
tz.offset :o2, 7200, 0, :EET
-
1
tz.offset :o3, 3600, 0, :CET
-
1
tz.offset :o4, 3600, 3600, :CEST
-
1
tz.offset :o5, 7200, 3600, :EEST
-
-
1
tz.transition 1879, 12, :o1, 52006653401, 21600
-
1
tz.transition 1894, 11, :o2, 26062154123, 10800
-
1
tz.transition 1942, 11, :o3, 58335973, 24
-
1
tz.transition 1943, 3, :o4, 58339501, 24
-
1
tz.transition 1943, 10, :o3, 58344037, 24
-
1
tz.transition 1944, 4, :o4, 58348405, 24
-
1
tz.transition 1944, 10, :o3, 58352773, 24
-
1
tz.transition 1945, 4, :o2, 29178571, 12
-
1
tz.transition 1979, 3, :o5, 291762000
-
1
tz.transition 1979, 9, :o2, 307576800
-
1
tz.transition 1980, 4, :o5, 323816400
-
1
tz.transition 1980, 9, :o2, 339026400
-
1
tz.transition 1981, 4, :o5, 355266000
-
1
tz.transition 1981, 9, :o2, 370393200
-
1
tz.transition 1982, 4, :o5, 386715600
-
1
tz.transition 1982, 9, :o2, 401846400
-
1
tz.transition 1983, 3, :o5, 417571200
-
1
tz.transition 1983, 9, :o2, 433296000
-
1
tz.transition 1984, 3, :o5, 449020800
-
1
tz.transition 1984, 9, :o2, 465350400
-
1
tz.transition 1985, 3, :o5, 481075200
-
1
tz.transition 1985, 9, :o2, 496800000
-
1
tz.transition 1986, 3, :o5, 512524800
-
1
tz.transition 1986, 9, :o2, 528249600
-
1
tz.transition 1987, 3, :o5, 543974400
-
1
tz.transition 1987, 9, :o2, 559699200
-
1
tz.transition 1988, 3, :o5, 575424000
-
1
tz.transition 1988, 9, :o2, 591148800
-
1
tz.transition 1989, 3, :o5, 606873600
-
1
tz.transition 1989, 9, :o2, 622598400
-
1
tz.transition 1990, 3, :o5, 638323200
-
1
tz.transition 1990, 9, :o2, 654652800
-
1
tz.transition 1991, 3, :o5, 670370400
-
1
tz.transition 1991, 9, :o2, 686091600
-
1
tz.transition 1992, 3, :o5, 701820000
-
1
tz.transition 1992, 9, :o2, 717541200
-
1
tz.transition 1993, 3, :o5, 733269600
-
1
tz.transition 1993, 9, :o2, 748990800
-
1
tz.transition 1994, 3, :o5, 764719200
-
1
tz.transition 1994, 9, :o2, 780440400
-
1
tz.transition 1995, 3, :o5, 796168800
-
1
tz.transition 1995, 9, :o2, 811890000
-
1
tz.transition 1996, 3, :o5, 828223200
-
1
tz.transition 1996, 10, :o2, 846363600
-
1
tz.transition 1997, 3, :o5, 859683600
-
1
tz.transition 1997, 10, :o2, 877827600
-
1
tz.transition 1998, 3, :o5, 891133200
-
1
tz.transition 1998, 10, :o2, 909277200
-
1
tz.transition 1999, 3, :o5, 922582800
-
1
tz.transition 1999, 10, :o2, 941331600
-
1
tz.transition 2000, 3, :o5, 954032400
-
1
tz.transition 2000, 10, :o2, 972781200
-
1
tz.transition 2001, 3, :o5, 985482000
-
1
tz.transition 2001, 10, :o2, 1004230800
-
1
tz.transition 2002, 3, :o5, 1017536400
-
1
tz.transition 2002, 10, :o2, 1035680400
-
1
tz.transition 2003, 3, :o5, 1048986000
-
1
tz.transition 2003, 10, :o2, 1067130000
-
1
tz.transition 2004, 3, :o5, 1080435600
-
1
tz.transition 2004, 10, :o2, 1099184400
-
1
tz.transition 2005, 3, :o5, 1111885200
-
1
tz.transition 2005, 10, :o2, 1130634000
-
1
tz.transition 2006, 3, :o5, 1143334800
-
1
tz.transition 2006, 10, :o2, 1162083600
-
1
tz.transition 2007, 3, :o5, 1174784400
-
1
tz.transition 2007, 10, :o2, 1193533200
-
1
tz.transition 2008, 3, :o5, 1206838800
-
1
tz.transition 2008, 10, :o2, 1224982800
-
1
tz.transition 2009, 3, :o5, 1238288400
-
1
tz.transition 2009, 10, :o2, 1256432400
-
1
tz.transition 2010, 3, :o5, 1269738000
-
1
tz.transition 2010, 10, :o2, 1288486800
-
1
tz.transition 2011, 3, :o5, 1301187600
-
1
tz.transition 2011, 10, :o2, 1319936400
-
1
tz.transition 2012, 3, :o5, 1332637200
-
1
tz.transition 2012, 10, :o2, 1351386000
-
1
tz.transition 2013, 3, :o5, 1364691600
-
1
tz.transition 2013, 10, :o2, 1382835600
-
1
tz.transition 2014, 3, :o5, 1396141200
-
1
tz.transition 2014, 10, :o2, 1414285200
-
1
tz.transition 2015, 3, :o5, 1427590800
-
1
tz.transition 2015, 10, :o2, 1445734800
-
1
tz.transition 2016, 3, :o5, 1459040400
-
1
tz.transition 2016, 10, :o2, 1477789200
-
1
tz.transition 2017, 3, :o5, 1490490000
-
1
tz.transition 2017, 10, :o2, 1509238800
-
1
tz.transition 2018, 3, :o5, 1521939600
-
1
tz.transition 2018, 10, :o2, 1540688400
-
1
tz.transition 2019, 3, :o5, 1553994000
-
1
tz.transition 2019, 10, :o2, 1572138000
-
1
tz.transition 2020, 3, :o5, 1585443600
-
1
tz.transition 2020, 10, :o2, 1603587600
-
1
tz.transition 2021, 3, :o5, 1616893200
-
1
tz.transition 2021, 10, :o2, 1635642000
-
1
tz.transition 2022, 3, :o5, 1648342800
-
1
tz.transition 2022, 10, :o2, 1667091600
-
1
tz.transition 2023, 3, :o5, 1679792400
-
1
tz.transition 2023, 10, :o2, 1698541200
-
1
tz.transition 2024, 3, :o5, 1711846800
-
1
tz.transition 2024, 10, :o2, 1729990800
-
1
tz.transition 2025, 3, :o5, 1743296400
-
1
tz.transition 2025, 10, :o2, 1761440400
-
1
tz.transition 2026, 3, :o5, 1774746000
-
1
tz.transition 2026, 10, :o2, 1792890000
-
1
tz.transition 2027, 3, :o5, 1806195600
-
1
tz.transition 2027, 10, :o2, 1824944400
-
1
tz.transition 2028, 3, :o5, 1837645200
-
1
tz.transition 2028, 10, :o2, 1856394000
-
1
tz.transition 2029, 3, :o5, 1869094800
-
1
tz.transition 2029, 10, :o2, 1887843600
-
1
tz.transition 2030, 3, :o5, 1901149200
-
1
tz.transition 2030, 10, :o2, 1919293200
-
1
tz.transition 2031, 3, :o5, 1932598800
-
1
tz.transition 2031, 10, :o2, 1950742800
-
1
tz.transition 2032, 3, :o5, 1964048400
-
1
tz.transition 2032, 10, :o2, 1982797200
-
1
tz.transition 2033, 3, :o5, 1995498000
-
1
tz.transition 2033, 10, :o2, 2014246800
-
1
tz.transition 2034, 3, :o5, 2026947600
-
1
tz.transition 2034, 10, :o2, 2045696400
-
1
tz.transition 2035, 3, :o5, 2058397200
-
1
tz.transition 2035, 10, :o2, 2077146000
-
1
tz.transition 2036, 3, :o5, 2090451600
-
1
tz.transition 2036, 10, :o2, 2108595600
-
1
tz.transition 2037, 3, :o5, 2121901200
-
1
tz.transition 2037, 10, :o2, 2140045200
-
1
tz.transition 2038, 3, :o5, 59172253, 24
-
1
tz.transition 2038, 10, :o2, 59177461, 24
-
1
tz.transition 2039, 3, :o5, 59180989, 24
-
1
tz.transition 2039, 10, :o2, 59186197, 24
-
1
tz.transition 2040, 3, :o5, 59189725, 24
-
1
tz.transition 2040, 10, :o2, 59194933, 24
-
1
tz.transition 2041, 3, :o5, 59198629, 24
-
1
tz.transition 2041, 10, :o2, 59203669, 24
-
1
tz.transition 2042, 3, :o5, 59207365, 24
-
1
tz.transition 2042, 10, :o2, 59212405, 24
-
1
tz.transition 2043, 3, :o5, 59216101, 24
-
1
tz.transition 2043, 10, :o2, 59221141, 24
-
1
tz.transition 2044, 3, :o5, 59224837, 24
-
1
tz.transition 2044, 10, :o2, 59230045, 24
-
1
tz.transition 2045, 3, :o5, 59233573, 24
-
1
tz.transition 2045, 10, :o2, 59238781, 24
-
1
tz.transition 2046, 3, :o5, 59242309, 24
-
1
tz.transition 2046, 10, :o2, 59247517, 24
-
1
tz.transition 2047, 3, :o5, 59251213, 24
-
1
tz.transition 2047, 10, :o2, 59256253, 24
-
1
tz.transition 2048, 3, :o5, 59259949, 24
-
1
tz.transition 2048, 10, :o2, 59264989, 24
-
1
tz.transition 2049, 3, :o5, 59268685, 24
-
1
tz.transition 2049, 10, :o2, 59273893, 24
-
1
tz.transition 2050, 3, :o5, 59277421, 24
-
1
tz.transition 2050, 10, :o2, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Stockholm
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Stockholm' do |tz|
-
1
tz.offset :o0, 4332, 0, :LMT
-
1
tz.offset :o1, 3614, 0, :SET
-
1
tz.offset :o2, 3600, 0, :CET
-
1
tz.offset :o3, 3600, 3600, :CEST
-
-
1
tz.transition 1878, 12, :o1, 17332923239, 7200
-
1
tz.transition 1899, 12, :o2, 104328883793, 43200
-
1
tz.transition 1916, 5, :o3, 29051981, 12
-
1
tz.transition 1916, 9, :o2, 58107299, 24
-
1
tz.transition 1980, 4, :o3, 323830800
-
1
tz.transition 1980, 9, :o2, 338950800
-
1
tz.transition 1981, 3, :o3, 354675600
-
1
tz.transition 1981, 9, :o2, 370400400
-
1
tz.transition 1982, 3, :o3, 386125200
-
1
tz.transition 1982, 9, :o2, 401850000
-
1
tz.transition 1983, 3, :o3, 417574800
-
1
tz.transition 1983, 9, :o2, 433299600
-
1
tz.transition 1984, 3, :o3, 449024400
-
1
tz.transition 1984, 9, :o2, 465354000
-
1
tz.transition 1985, 3, :o3, 481078800
-
1
tz.transition 1985, 9, :o2, 496803600
-
1
tz.transition 1986, 3, :o3, 512528400
-
1
tz.transition 1986, 9, :o2, 528253200
-
1
tz.transition 1987, 3, :o3, 543978000
-
1
tz.transition 1987, 9, :o2, 559702800
-
1
tz.transition 1988, 3, :o3, 575427600
-
1
tz.transition 1988, 9, :o2, 591152400
-
1
tz.transition 1989, 3, :o3, 606877200
-
1
tz.transition 1989, 9, :o2, 622602000
-
1
tz.transition 1990, 3, :o3, 638326800
-
1
tz.transition 1990, 9, :o2, 654656400
-
1
tz.transition 1991, 3, :o3, 670381200
-
1
tz.transition 1991, 9, :o2, 686106000
-
1
tz.transition 1992, 3, :o3, 701830800
-
1
tz.transition 1992, 9, :o2, 717555600
-
1
tz.transition 1993, 3, :o3, 733280400
-
1
tz.transition 1993, 9, :o2, 749005200
-
1
tz.transition 1994, 3, :o3, 764730000
-
1
tz.transition 1994, 9, :o2, 780454800
-
1
tz.transition 1995, 3, :o3, 796179600
-
1
tz.transition 1995, 9, :o2, 811904400
-
1
tz.transition 1996, 3, :o3, 828234000
-
1
tz.transition 1996, 10, :o2, 846378000
-
1
tz.transition 1997, 3, :o3, 859683600
-
1
tz.transition 1997, 10, :o2, 877827600
-
1
tz.transition 1998, 3, :o3, 891133200
-
1
tz.transition 1998, 10, :o2, 909277200
-
1
tz.transition 1999, 3, :o3, 922582800
-
1
tz.transition 1999, 10, :o2, 941331600
-
1
tz.transition 2000, 3, :o3, 954032400
-
1
tz.transition 2000, 10, :o2, 972781200
-
1
tz.transition 2001, 3, :o3, 985482000
-
1
tz.transition 2001, 10, :o2, 1004230800
-
1
tz.transition 2002, 3, :o3, 1017536400
-
1
tz.transition 2002, 10, :o2, 1035680400
-
1
tz.transition 2003, 3, :o3, 1048986000
-
1
tz.transition 2003, 10, :o2, 1067130000
-
1
tz.transition 2004, 3, :o3, 1080435600
-
1
tz.transition 2004, 10, :o2, 1099184400
-
1
tz.transition 2005, 3, :o3, 1111885200
-
1
tz.transition 2005, 10, :o2, 1130634000
-
1
tz.transition 2006, 3, :o3, 1143334800
-
1
tz.transition 2006, 10, :o2, 1162083600
-
1
tz.transition 2007, 3, :o3, 1174784400
-
1
tz.transition 2007, 10, :o2, 1193533200
-
1
tz.transition 2008, 3, :o3, 1206838800
-
1
tz.transition 2008, 10, :o2, 1224982800
-
1
tz.transition 2009, 3, :o3, 1238288400
-
1
tz.transition 2009, 10, :o2, 1256432400
-
1
tz.transition 2010, 3, :o3, 1269738000
-
1
tz.transition 2010, 10, :o2, 1288486800
-
1
tz.transition 2011, 3, :o3, 1301187600
-
1
tz.transition 2011, 10, :o2, 1319936400
-
1
tz.transition 2012, 3, :o3, 1332637200
-
1
tz.transition 2012, 10, :o2, 1351386000
-
1
tz.transition 2013, 3, :o3, 1364691600
-
1
tz.transition 2013, 10, :o2, 1382835600
-
1
tz.transition 2014, 3, :o3, 1396141200
-
1
tz.transition 2014, 10, :o2, 1414285200
-
1
tz.transition 2015, 3, :o3, 1427590800
-
1
tz.transition 2015, 10, :o2, 1445734800
-
1
tz.transition 2016, 3, :o3, 1459040400
-
1
tz.transition 2016, 10, :o2, 1477789200
-
1
tz.transition 2017, 3, :o3, 1490490000
-
1
tz.transition 2017, 10, :o2, 1509238800
-
1
tz.transition 2018, 3, :o3, 1521939600
-
1
tz.transition 2018, 10, :o2, 1540688400
-
1
tz.transition 2019, 3, :o3, 1553994000
-
1
tz.transition 2019, 10, :o2, 1572138000
-
1
tz.transition 2020, 3, :o3, 1585443600
-
1
tz.transition 2020, 10, :o2, 1603587600
-
1
tz.transition 2021, 3, :o3, 1616893200
-
1
tz.transition 2021, 10, :o2, 1635642000
-
1
tz.transition 2022, 3, :o3, 1648342800
-
1
tz.transition 2022, 10, :o2, 1667091600
-
1
tz.transition 2023, 3, :o3, 1679792400
-
1
tz.transition 2023, 10, :o2, 1698541200
-
1
tz.transition 2024, 3, :o3, 1711846800
-
1
tz.transition 2024, 10, :o2, 1729990800
-
1
tz.transition 2025, 3, :o3, 1743296400
-
1
tz.transition 2025, 10, :o2, 1761440400
-
1
tz.transition 2026, 3, :o3, 1774746000
-
1
tz.transition 2026, 10, :o2, 1792890000
-
1
tz.transition 2027, 3, :o3, 1806195600
-
1
tz.transition 2027, 10, :o2, 1824944400
-
1
tz.transition 2028, 3, :o3, 1837645200
-
1
tz.transition 2028, 10, :o2, 1856394000
-
1
tz.transition 2029, 3, :o3, 1869094800
-
1
tz.transition 2029, 10, :o2, 1887843600
-
1
tz.transition 2030, 3, :o3, 1901149200
-
1
tz.transition 2030, 10, :o2, 1919293200
-
1
tz.transition 2031, 3, :o3, 1932598800
-
1
tz.transition 2031, 10, :o2, 1950742800
-
1
tz.transition 2032, 3, :o3, 1964048400
-
1
tz.transition 2032, 10, :o2, 1982797200
-
1
tz.transition 2033, 3, :o3, 1995498000
-
1
tz.transition 2033, 10, :o2, 2014246800
-
1
tz.transition 2034, 3, :o3, 2026947600
-
1
tz.transition 2034, 10, :o2, 2045696400
-
1
tz.transition 2035, 3, :o3, 2058397200
-
1
tz.transition 2035, 10, :o2, 2077146000
-
1
tz.transition 2036, 3, :o3, 2090451600
-
1
tz.transition 2036, 10, :o2, 2108595600
-
1
tz.transition 2037, 3, :o3, 2121901200
-
1
tz.transition 2037, 10, :o2, 2140045200
-
1
tz.transition 2038, 3, :o3, 59172253, 24
-
1
tz.transition 2038, 10, :o2, 59177461, 24
-
1
tz.transition 2039, 3, :o3, 59180989, 24
-
1
tz.transition 2039, 10, :o2, 59186197, 24
-
1
tz.transition 2040, 3, :o3, 59189725, 24
-
1
tz.transition 2040, 10, :o2, 59194933, 24
-
1
tz.transition 2041, 3, :o3, 59198629, 24
-
1
tz.transition 2041, 10, :o2, 59203669, 24
-
1
tz.transition 2042, 3, :o3, 59207365, 24
-
1
tz.transition 2042, 10, :o2, 59212405, 24
-
1
tz.transition 2043, 3, :o3, 59216101, 24
-
1
tz.transition 2043, 10, :o2, 59221141, 24
-
1
tz.transition 2044, 3, :o3, 59224837, 24
-
1
tz.transition 2044, 10, :o2, 59230045, 24
-
1
tz.transition 2045, 3, :o3, 59233573, 24
-
1
tz.transition 2045, 10, :o2, 59238781, 24
-
1
tz.transition 2046, 3, :o3, 59242309, 24
-
1
tz.transition 2046, 10, :o2, 59247517, 24
-
1
tz.transition 2047, 3, :o3, 59251213, 24
-
1
tz.transition 2047, 10, :o2, 59256253, 24
-
1
tz.transition 2048, 3, :o3, 59259949, 24
-
1
tz.transition 2048, 10, :o2, 59264989, 24
-
1
tz.transition 2049, 3, :o3, 59268685, 24
-
1
tz.transition 2049, 10, :o2, 59273893, 24
-
1
tz.transition 2050, 3, :o3, 59277421, 24
-
1
tz.transition 2050, 10, :o2, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Tallinn
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Tallinn' do |tz|
-
1
tz.offset :o0, 5940, 0, :LMT
-
1
tz.offset :o1, 5940, 0, :TMT
-
1
tz.offset :o2, 3600, 0, :CET
-
1
tz.offset :o3, 3600, 3600, :CEST
-
1
tz.offset :o4, 7200, 0, :EET
-
1
tz.offset :o5, 10800, 0, :MSK
-
1
tz.offset :o6, 10800, 3600, :MSD
-
1
tz.offset :o7, 7200, 3600, :EEST
-
-
1
tz.transition 1879, 12, :o1, 385234469, 160
-
1
tz.transition 1918, 1, :o2, 387460069, 160
-
1
tz.transition 1918, 4, :o3, 58120765, 24
-
1
tz.transition 1918, 9, :o2, 58124461, 24
-
1
tz.transition 1919, 6, :o1, 58131371, 24
-
1
tz.transition 1921, 4, :o4, 387649669, 160
-
1
tz.transition 1940, 8, :o5, 29158169, 12
-
1
tz.transition 1941, 9, :o3, 19442019, 8
-
1
tz.transition 1942, 11, :o2, 58335973, 24
-
1
tz.transition 1943, 3, :o3, 58339501, 24
-
1
tz.transition 1943, 10, :o2, 58344037, 24
-
1
tz.transition 1944, 4, :o3, 58348405, 24
-
1
tz.transition 1944, 9, :o5, 29176265, 12
-
1
tz.transition 1981, 3, :o6, 354920400
-
1
tz.transition 1981, 9, :o5, 370728000
-
1
tz.transition 1982, 3, :o6, 386456400
-
1
tz.transition 1982, 9, :o5, 402264000
-
1
tz.transition 1983, 3, :o6, 417992400
-
1
tz.transition 1983, 9, :o5, 433800000
-
1
tz.transition 1984, 3, :o6, 449614800
-
1
tz.transition 1984, 9, :o5, 465346800
-
1
tz.transition 1985, 3, :o6, 481071600
-
1
tz.transition 1985, 9, :o5, 496796400
-
1
tz.transition 1986, 3, :o6, 512521200
-
1
tz.transition 1986, 9, :o5, 528246000
-
1
tz.transition 1987, 3, :o6, 543970800
-
1
tz.transition 1987, 9, :o5, 559695600
-
1
tz.transition 1988, 3, :o6, 575420400
-
1
tz.transition 1988, 9, :o5, 591145200
-
1
tz.transition 1989, 3, :o7, 606870000
-
1
tz.transition 1989, 9, :o4, 622598400
-
1
tz.transition 1990, 3, :o7, 638323200
-
1
tz.transition 1990, 9, :o4, 654652800
-
1
tz.transition 1991, 3, :o7, 670377600
-
1
tz.transition 1991, 9, :o4, 686102400
-
1
tz.transition 1992, 3, :o7, 701827200
-
1
tz.transition 1992, 9, :o4, 717552000
-
1
tz.transition 1993, 3, :o7, 733276800
-
1
tz.transition 1993, 9, :o4, 749001600
-
1
tz.transition 1994, 3, :o7, 764726400
-
1
tz.transition 1994, 9, :o4, 780451200
-
1
tz.transition 1995, 3, :o7, 796176000
-
1
tz.transition 1995, 9, :o4, 811900800
-
1
tz.transition 1996, 3, :o7, 828230400
-
1
tz.transition 1996, 10, :o4, 846374400
-
1
tz.transition 1997, 3, :o7, 859680000
-
1
tz.transition 1997, 10, :o4, 877824000
-
1
tz.transition 1998, 3, :o7, 891129600
-
1
tz.transition 1998, 10, :o4, 909277200
-
1
tz.transition 1999, 3, :o7, 922582800
-
1
tz.transition 1999, 10, :o4, 941331600
-
1
tz.transition 2002, 3, :o7, 1017536400
-
1
tz.transition 2002, 10, :o4, 1035680400
-
1
tz.transition 2003, 3, :o7, 1048986000
-
1
tz.transition 2003, 10, :o4, 1067130000
-
1
tz.transition 2004, 3, :o7, 1080435600
-
1
tz.transition 2004, 10, :o4, 1099184400
-
1
tz.transition 2005, 3, :o7, 1111885200
-
1
tz.transition 2005, 10, :o4, 1130634000
-
1
tz.transition 2006, 3, :o7, 1143334800
-
1
tz.transition 2006, 10, :o4, 1162083600
-
1
tz.transition 2007, 3, :o7, 1174784400
-
1
tz.transition 2007, 10, :o4, 1193533200
-
1
tz.transition 2008, 3, :o7, 1206838800
-
1
tz.transition 2008, 10, :o4, 1224982800
-
1
tz.transition 2009, 3, :o7, 1238288400
-
1
tz.transition 2009, 10, :o4, 1256432400
-
1
tz.transition 2010, 3, :o7, 1269738000
-
1
tz.transition 2010, 10, :o4, 1288486800
-
1
tz.transition 2011, 3, :o7, 1301187600
-
1
tz.transition 2011, 10, :o4, 1319936400
-
1
tz.transition 2012, 3, :o7, 1332637200
-
1
tz.transition 2012, 10, :o4, 1351386000
-
1
tz.transition 2013, 3, :o7, 1364691600
-
1
tz.transition 2013, 10, :o4, 1382835600
-
1
tz.transition 2014, 3, :o7, 1396141200
-
1
tz.transition 2014, 10, :o4, 1414285200
-
1
tz.transition 2015, 3, :o7, 1427590800
-
1
tz.transition 2015, 10, :o4, 1445734800
-
1
tz.transition 2016, 3, :o7, 1459040400
-
1
tz.transition 2016, 10, :o4, 1477789200
-
1
tz.transition 2017, 3, :o7, 1490490000
-
1
tz.transition 2017, 10, :o4, 1509238800
-
1
tz.transition 2018, 3, :o7, 1521939600
-
1
tz.transition 2018, 10, :o4, 1540688400
-
1
tz.transition 2019, 3, :o7, 1553994000
-
1
tz.transition 2019, 10, :o4, 1572138000
-
1
tz.transition 2020, 3, :o7, 1585443600
-
1
tz.transition 2020, 10, :o4, 1603587600
-
1
tz.transition 2021, 3, :o7, 1616893200
-
1
tz.transition 2021, 10, :o4, 1635642000
-
1
tz.transition 2022, 3, :o7, 1648342800
-
1
tz.transition 2022, 10, :o4, 1667091600
-
1
tz.transition 2023, 3, :o7, 1679792400
-
1
tz.transition 2023, 10, :o4, 1698541200
-
1
tz.transition 2024, 3, :o7, 1711846800
-
1
tz.transition 2024, 10, :o4, 1729990800
-
1
tz.transition 2025, 3, :o7, 1743296400
-
1
tz.transition 2025, 10, :o4, 1761440400
-
1
tz.transition 2026, 3, :o7, 1774746000
-
1
tz.transition 2026, 10, :o4, 1792890000
-
1
tz.transition 2027, 3, :o7, 1806195600
-
1
tz.transition 2027, 10, :o4, 1824944400
-
1
tz.transition 2028, 3, :o7, 1837645200
-
1
tz.transition 2028, 10, :o4, 1856394000
-
1
tz.transition 2029, 3, :o7, 1869094800
-
1
tz.transition 2029, 10, :o4, 1887843600
-
1
tz.transition 2030, 3, :o7, 1901149200
-
1
tz.transition 2030, 10, :o4, 1919293200
-
1
tz.transition 2031, 3, :o7, 1932598800
-
1
tz.transition 2031, 10, :o4, 1950742800
-
1
tz.transition 2032, 3, :o7, 1964048400
-
1
tz.transition 2032, 10, :o4, 1982797200
-
1
tz.transition 2033, 3, :o7, 1995498000
-
1
tz.transition 2033, 10, :o4, 2014246800
-
1
tz.transition 2034, 3, :o7, 2026947600
-
1
tz.transition 2034, 10, :o4, 2045696400
-
1
tz.transition 2035, 3, :o7, 2058397200
-
1
tz.transition 2035, 10, :o4, 2077146000
-
1
tz.transition 2036, 3, :o7, 2090451600
-
1
tz.transition 2036, 10, :o4, 2108595600
-
1
tz.transition 2037, 3, :o7, 2121901200
-
1
tz.transition 2037, 10, :o4, 2140045200
-
1
tz.transition 2038, 3, :o7, 59172253, 24
-
1
tz.transition 2038, 10, :o4, 59177461, 24
-
1
tz.transition 2039, 3, :o7, 59180989, 24
-
1
tz.transition 2039, 10, :o4, 59186197, 24
-
1
tz.transition 2040, 3, :o7, 59189725, 24
-
1
tz.transition 2040, 10, :o4, 59194933, 24
-
1
tz.transition 2041, 3, :o7, 59198629, 24
-
1
tz.transition 2041, 10, :o4, 59203669, 24
-
1
tz.transition 2042, 3, :o7, 59207365, 24
-
1
tz.transition 2042, 10, :o4, 59212405, 24
-
1
tz.transition 2043, 3, :o7, 59216101, 24
-
1
tz.transition 2043, 10, :o4, 59221141, 24
-
1
tz.transition 2044, 3, :o7, 59224837, 24
-
1
tz.transition 2044, 10, :o4, 59230045, 24
-
1
tz.transition 2045, 3, :o7, 59233573, 24
-
1
tz.transition 2045, 10, :o4, 59238781, 24
-
1
tz.transition 2046, 3, :o7, 59242309, 24
-
1
tz.transition 2046, 10, :o4, 59247517, 24
-
1
tz.transition 2047, 3, :o7, 59251213, 24
-
1
tz.transition 2047, 10, :o4, 59256253, 24
-
1
tz.transition 2048, 3, :o7, 59259949, 24
-
1
tz.transition 2048, 10, :o4, 59264989, 24
-
1
tz.transition 2049, 3, :o7, 59268685, 24
-
1
tz.transition 2049, 10, :o4, 59273893, 24
-
1
tz.transition 2050, 3, :o7, 59277421, 24
-
1
tz.transition 2050, 10, :o4, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Vienna
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Vienna' do |tz|
-
1
tz.offset :o0, 3920, 0, :LMT
-
1
tz.offset :o1, 3600, 0, :CET
-
1
tz.offset :o2, 3600, 3600, :CEST
-
-
1
tz.transition 1893, 3, :o1, 2605558811, 1080
-
1
tz.transition 1916, 4, :o2, 29051813, 12
-
1
tz.transition 1916, 9, :o1, 58107299, 24
-
1
tz.transition 1917, 4, :o2, 58112029, 24
-
1
tz.transition 1917, 9, :o1, 58115725, 24
-
1
tz.transition 1918, 4, :o2, 58120765, 24
-
1
tz.transition 1918, 9, :o1, 58124461, 24
-
1
tz.transition 1920, 4, :o2, 58138069, 24
-
1
tz.transition 1920, 9, :o1, 58141933, 24
-
1
tz.transition 1940, 4, :o2, 58313293, 24
-
1
tz.transition 1942, 11, :o1, 58335973, 24
-
1
tz.transition 1943, 3, :o2, 58339501, 24
-
1
tz.transition 1943, 10, :o1, 58344037, 24
-
1
tz.transition 1944, 4, :o2, 58348405, 24
-
1
tz.transition 1944, 10, :o1, 58352773, 24
-
1
tz.transition 1945, 4, :o2, 58357141, 24
-
1
tz.transition 1945, 4, :o1, 58357381, 24
-
1
tz.transition 1946, 4, :o2, 58366189, 24
-
1
tz.transition 1946, 10, :o1, 58370389, 24
-
1
tz.transition 1947, 4, :o2, 58374757, 24
-
1
tz.transition 1947, 10, :o1, 58379125, 24
-
1
tz.transition 1948, 4, :o2, 58383829, 24
-
1
tz.transition 1948, 10, :o1, 58387861, 24
-
1
tz.transition 1980, 4, :o2, 323823600
-
1
tz.transition 1980, 9, :o1, 338940000
-
1
tz.transition 1981, 3, :o2, 354675600
-
1
tz.transition 1981, 9, :o1, 370400400
-
1
tz.transition 1982, 3, :o2, 386125200
-
1
tz.transition 1982, 9, :o1, 401850000
-
1
tz.transition 1983, 3, :o2, 417574800
-
1
tz.transition 1983, 9, :o1, 433299600
-
1
tz.transition 1984, 3, :o2, 449024400
-
1
tz.transition 1984, 9, :o1, 465354000
-
1
tz.transition 1985, 3, :o2, 481078800
-
1
tz.transition 1985, 9, :o1, 496803600
-
1
tz.transition 1986, 3, :o2, 512528400
-
1
tz.transition 1986, 9, :o1, 528253200
-
1
tz.transition 1987, 3, :o2, 543978000
-
1
tz.transition 1987, 9, :o1, 559702800
-
1
tz.transition 1988, 3, :o2, 575427600
-
1
tz.transition 1988, 9, :o1, 591152400
-
1
tz.transition 1989, 3, :o2, 606877200
-
1
tz.transition 1989, 9, :o1, 622602000
-
1
tz.transition 1990, 3, :o2, 638326800
-
1
tz.transition 1990, 9, :o1, 654656400
-
1
tz.transition 1991, 3, :o2, 670381200
-
1
tz.transition 1991, 9, :o1, 686106000
-
1
tz.transition 1992, 3, :o2, 701830800
-
1
tz.transition 1992, 9, :o1, 717555600
-
1
tz.transition 1993, 3, :o2, 733280400
-
1
tz.transition 1993, 9, :o1, 749005200
-
1
tz.transition 1994, 3, :o2, 764730000
-
1
tz.transition 1994, 9, :o1, 780454800
-
1
tz.transition 1995, 3, :o2, 796179600
-
1
tz.transition 1995, 9, :o1, 811904400
-
1
tz.transition 1996, 3, :o2, 828234000
-
1
tz.transition 1996, 10, :o1, 846378000
-
1
tz.transition 1997, 3, :o2, 859683600
-
1
tz.transition 1997, 10, :o1, 877827600
-
1
tz.transition 1998, 3, :o2, 891133200
-
1
tz.transition 1998, 10, :o1, 909277200
-
1
tz.transition 1999, 3, :o2, 922582800
-
1
tz.transition 1999, 10, :o1, 941331600
-
1
tz.transition 2000, 3, :o2, 954032400
-
1
tz.transition 2000, 10, :o1, 972781200
-
1
tz.transition 2001, 3, :o2, 985482000
-
1
tz.transition 2001, 10, :o1, 1004230800
-
1
tz.transition 2002, 3, :o2, 1017536400
-
1
tz.transition 2002, 10, :o1, 1035680400
-
1
tz.transition 2003, 3, :o2, 1048986000
-
1
tz.transition 2003, 10, :o1, 1067130000
-
1
tz.transition 2004, 3, :o2, 1080435600
-
1
tz.transition 2004, 10, :o1, 1099184400
-
1
tz.transition 2005, 3, :o2, 1111885200
-
1
tz.transition 2005, 10, :o1, 1130634000
-
1
tz.transition 2006, 3, :o2, 1143334800
-
1
tz.transition 2006, 10, :o1, 1162083600
-
1
tz.transition 2007, 3, :o2, 1174784400
-
1
tz.transition 2007, 10, :o1, 1193533200
-
1
tz.transition 2008, 3, :o2, 1206838800
-
1
tz.transition 2008, 10, :o1, 1224982800
-
1
tz.transition 2009, 3, :o2, 1238288400
-
1
tz.transition 2009, 10, :o1, 1256432400
-
1
tz.transition 2010, 3, :o2, 1269738000
-
1
tz.transition 2010, 10, :o1, 1288486800
-
1
tz.transition 2011, 3, :o2, 1301187600
-
1
tz.transition 2011, 10, :o1, 1319936400
-
1
tz.transition 2012, 3, :o2, 1332637200
-
1
tz.transition 2012, 10, :o1, 1351386000
-
1
tz.transition 2013, 3, :o2, 1364691600
-
1
tz.transition 2013, 10, :o1, 1382835600
-
1
tz.transition 2014, 3, :o2, 1396141200
-
1
tz.transition 2014, 10, :o1, 1414285200
-
1
tz.transition 2015, 3, :o2, 1427590800
-
1
tz.transition 2015, 10, :o1, 1445734800
-
1
tz.transition 2016, 3, :o2, 1459040400
-
1
tz.transition 2016, 10, :o1, 1477789200
-
1
tz.transition 2017, 3, :o2, 1490490000
-
1
tz.transition 2017, 10, :o1, 1509238800
-
1
tz.transition 2018, 3, :o2, 1521939600
-
1
tz.transition 2018, 10, :o1, 1540688400
-
1
tz.transition 2019, 3, :o2, 1553994000
-
1
tz.transition 2019, 10, :o1, 1572138000
-
1
tz.transition 2020, 3, :o2, 1585443600
-
1
tz.transition 2020, 10, :o1, 1603587600
-
1
tz.transition 2021, 3, :o2, 1616893200
-
1
tz.transition 2021, 10, :o1, 1635642000
-
1
tz.transition 2022, 3, :o2, 1648342800
-
1
tz.transition 2022, 10, :o1, 1667091600
-
1
tz.transition 2023, 3, :o2, 1679792400
-
1
tz.transition 2023, 10, :o1, 1698541200
-
1
tz.transition 2024, 3, :o2, 1711846800
-
1
tz.transition 2024, 10, :o1, 1729990800
-
1
tz.transition 2025, 3, :o2, 1743296400
-
1
tz.transition 2025, 10, :o1, 1761440400
-
1
tz.transition 2026, 3, :o2, 1774746000
-
1
tz.transition 2026, 10, :o1, 1792890000
-
1
tz.transition 2027, 3, :o2, 1806195600
-
1
tz.transition 2027, 10, :o1, 1824944400
-
1
tz.transition 2028, 3, :o2, 1837645200
-
1
tz.transition 2028, 10, :o1, 1856394000
-
1
tz.transition 2029, 3, :o2, 1869094800
-
1
tz.transition 2029, 10, :o1, 1887843600
-
1
tz.transition 2030, 3, :o2, 1901149200
-
1
tz.transition 2030, 10, :o1, 1919293200
-
1
tz.transition 2031, 3, :o2, 1932598800
-
1
tz.transition 2031, 10, :o1, 1950742800
-
1
tz.transition 2032, 3, :o2, 1964048400
-
1
tz.transition 2032, 10, :o1, 1982797200
-
1
tz.transition 2033, 3, :o2, 1995498000
-
1
tz.transition 2033, 10, :o1, 2014246800
-
1
tz.transition 2034, 3, :o2, 2026947600
-
1
tz.transition 2034, 10, :o1, 2045696400
-
1
tz.transition 2035, 3, :o2, 2058397200
-
1
tz.transition 2035, 10, :o1, 2077146000
-
1
tz.transition 2036, 3, :o2, 2090451600
-
1
tz.transition 2036, 10, :o1, 2108595600
-
1
tz.transition 2037, 3, :o2, 2121901200
-
1
tz.transition 2037, 10, :o1, 2140045200
-
1
tz.transition 2038, 3, :o2, 59172253, 24
-
1
tz.transition 2038, 10, :o1, 59177461, 24
-
1
tz.transition 2039, 3, :o2, 59180989, 24
-
1
tz.transition 2039, 10, :o1, 59186197, 24
-
1
tz.transition 2040, 3, :o2, 59189725, 24
-
1
tz.transition 2040, 10, :o1, 59194933, 24
-
1
tz.transition 2041, 3, :o2, 59198629, 24
-
1
tz.transition 2041, 10, :o1, 59203669, 24
-
1
tz.transition 2042, 3, :o2, 59207365, 24
-
1
tz.transition 2042, 10, :o1, 59212405, 24
-
1
tz.transition 2043, 3, :o2, 59216101, 24
-
1
tz.transition 2043, 10, :o1, 59221141, 24
-
1
tz.transition 2044, 3, :o2, 59224837, 24
-
1
tz.transition 2044, 10, :o1, 59230045, 24
-
1
tz.transition 2045, 3, :o2, 59233573, 24
-
1
tz.transition 2045, 10, :o1, 59238781, 24
-
1
tz.transition 2046, 3, :o2, 59242309, 24
-
1
tz.transition 2046, 10, :o1, 59247517, 24
-
1
tz.transition 2047, 3, :o2, 59251213, 24
-
1
tz.transition 2047, 10, :o1, 59256253, 24
-
1
tz.transition 2048, 3, :o2, 59259949, 24
-
1
tz.transition 2048, 10, :o1, 59264989, 24
-
1
tz.transition 2049, 3, :o2, 59268685, 24
-
1
tz.transition 2049, 10, :o1, 59273893, 24
-
1
tz.transition 2050, 3, :o2, 59277421, 24
-
1
tz.transition 2050, 10, :o1, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Vilnius
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Vilnius' do |tz|
-
1
tz.offset :o0, 6076, 0, :LMT
-
1
tz.offset :o1, 5040, 0, :WMT
-
1
tz.offset :o2, 5736, 0, :KMT
-
1
tz.offset :o3, 3600, 0, :CET
-
1
tz.offset :o4, 7200, 0, :EET
-
1
tz.offset :o5, 10800, 0, :MSK
-
1
tz.offset :o6, 3600, 3600, :CEST
-
1
tz.offset :o7, 10800, 3600, :MSD
-
1
tz.offset :o8, 7200, 3600, :EEST
-
-
1
tz.transition 1879, 12, :o1, 52006653281, 21600
-
1
tz.transition 1916, 12, :o2, 290547533, 120
-
1
tz.transition 1919, 10, :o3, 8720069161, 3600
-
1
tz.transition 1920, 7, :o4, 58140419, 24
-
1
tz.transition 1920, 10, :o3, 29071277, 12
-
1
tz.transition 1940, 8, :o5, 58316267, 24
-
1
tz.transition 1941, 6, :o6, 19441355, 8
-
1
tz.transition 1942, 11, :o3, 58335973, 24
-
1
tz.transition 1943, 3, :o6, 58339501, 24
-
1
tz.transition 1943, 10, :o3, 58344037, 24
-
1
tz.transition 1944, 4, :o6, 58348405, 24
-
1
tz.transition 1944, 7, :o5, 29175641, 12
-
1
tz.transition 1981, 3, :o7, 354920400
-
1
tz.transition 1981, 9, :o5, 370728000
-
1
tz.transition 1982, 3, :o7, 386456400
-
1
tz.transition 1982, 9, :o5, 402264000
-
1
tz.transition 1983, 3, :o7, 417992400
-
1
tz.transition 1983, 9, :o5, 433800000
-
1
tz.transition 1984, 3, :o7, 449614800
-
1
tz.transition 1984, 9, :o5, 465346800
-
1
tz.transition 1985, 3, :o7, 481071600
-
1
tz.transition 1985, 9, :o5, 496796400
-
1
tz.transition 1986, 3, :o7, 512521200
-
1
tz.transition 1986, 9, :o5, 528246000
-
1
tz.transition 1987, 3, :o7, 543970800
-
1
tz.transition 1987, 9, :o5, 559695600
-
1
tz.transition 1988, 3, :o7, 575420400
-
1
tz.transition 1988, 9, :o5, 591145200
-
1
tz.transition 1989, 3, :o7, 606870000
-
1
tz.transition 1989, 9, :o5, 622594800
-
1
tz.transition 1990, 3, :o7, 638319600
-
1
tz.transition 1990, 9, :o5, 654649200
-
1
tz.transition 1991, 3, :o8, 670374000
-
1
tz.transition 1991, 9, :o4, 686102400
-
1
tz.transition 1992, 3, :o8, 701827200
-
1
tz.transition 1992, 9, :o4, 717552000
-
1
tz.transition 1993, 3, :o8, 733276800
-
1
tz.transition 1993, 9, :o4, 749001600
-
1
tz.transition 1994, 3, :o8, 764726400
-
1
tz.transition 1994, 9, :o4, 780451200
-
1
tz.transition 1995, 3, :o8, 796176000
-
1
tz.transition 1995, 9, :o4, 811900800
-
1
tz.transition 1996, 3, :o8, 828230400
-
1
tz.transition 1996, 10, :o4, 846374400
-
1
tz.transition 1997, 3, :o8, 859680000
-
1
tz.transition 1997, 10, :o4, 877824000
-
1
tz.transition 1998, 3, :o6, 891133200
-
1
tz.transition 1998, 10, :o3, 909277200
-
1
tz.transition 1999, 3, :o6, 922582800
-
1
tz.transition 1999, 10, :o4, 941331600
-
1
tz.transition 2003, 3, :o8, 1048986000
-
1
tz.transition 2003, 10, :o4, 1067130000
-
1
tz.transition 2004, 3, :o8, 1080435600
-
1
tz.transition 2004, 10, :o4, 1099184400
-
1
tz.transition 2005, 3, :o8, 1111885200
-
1
tz.transition 2005, 10, :o4, 1130634000
-
1
tz.transition 2006, 3, :o8, 1143334800
-
1
tz.transition 2006, 10, :o4, 1162083600
-
1
tz.transition 2007, 3, :o8, 1174784400
-
1
tz.transition 2007, 10, :o4, 1193533200
-
1
tz.transition 2008, 3, :o8, 1206838800
-
1
tz.transition 2008, 10, :o4, 1224982800
-
1
tz.transition 2009, 3, :o8, 1238288400
-
1
tz.transition 2009, 10, :o4, 1256432400
-
1
tz.transition 2010, 3, :o8, 1269738000
-
1
tz.transition 2010, 10, :o4, 1288486800
-
1
tz.transition 2011, 3, :o8, 1301187600
-
1
tz.transition 2011, 10, :o4, 1319936400
-
1
tz.transition 2012, 3, :o8, 1332637200
-
1
tz.transition 2012, 10, :o4, 1351386000
-
1
tz.transition 2013, 3, :o8, 1364691600
-
1
tz.transition 2013, 10, :o4, 1382835600
-
1
tz.transition 2014, 3, :o8, 1396141200
-
1
tz.transition 2014, 10, :o4, 1414285200
-
1
tz.transition 2015, 3, :o8, 1427590800
-
1
tz.transition 2015, 10, :o4, 1445734800
-
1
tz.transition 2016, 3, :o8, 1459040400
-
1
tz.transition 2016, 10, :o4, 1477789200
-
1
tz.transition 2017, 3, :o8, 1490490000
-
1
tz.transition 2017, 10, :o4, 1509238800
-
1
tz.transition 2018, 3, :o8, 1521939600
-
1
tz.transition 2018, 10, :o4, 1540688400
-
1
tz.transition 2019, 3, :o8, 1553994000
-
1
tz.transition 2019, 10, :o4, 1572138000
-
1
tz.transition 2020, 3, :o8, 1585443600
-
1
tz.transition 2020, 10, :o4, 1603587600
-
1
tz.transition 2021, 3, :o8, 1616893200
-
1
tz.transition 2021, 10, :o4, 1635642000
-
1
tz.transition 2022, 3, :o8, 1648342800
-
1
tz.transition 2022, 10, :o4, 1667091600
-
1
tz.transition 2023, 3, :o8, 1679792400
-
1
tz.transition 2023, 10, :o4, 1698541200
-
1
tz.transition 2024, 3, :o8, 1711846800
-
1
tz.transition 2024, 10, :o4, 1729990800
-
1
tz.transition 2025, 3, :o8, 1743296400
-
1
tz.transition 2025, 10, :o4, 1761440400
-
1
tz.transition 2026, 3, :o8, 1774746000
-
1
tz.transition 2026, 10, :o4, 1792890000
-
1
tz.transition 2027, 3, :o8, 1806195600
-
1
tz.transition 2027, 10, :o4, 1824944400
-
1
tz.transition 2028, 3, :o8, 1837645200
-
1
tz.transition 2028, 10, :o4, 1856394000
-
1
tz.transition 2029, 3, :o8, 1869094800
-
1
tz.transition 2029, 10, :o4, 1887843600
-
1
tz.transition 2030, 3, :o8, 1901149200
-
1
tz.transition 2030, 10, :o4, 1919293200
-
1
tz.transition 2031, 3, :o8, 1932598800
-
1
tz.transition 2031, 10, :o4, 1950742800
-
1
tz.transition 2032, 3, :o8, 1964048400
-
1
tz.transition 2032, 10, :o4, 1982797200
-
1
tz.transition 2033, 3, :o8, 1995498000
-
1
tz.transition 2033, 10, :o4, 2014246800
-
1
tz.transition 2034, 3, :o8, 2026947600
-
1
tz.transition 2034, 10, :o4, 2045696400
-
1
tz.transition 2035, 3, :o8, 2058397200
-
1
tz.transition 2035, 10, :o4, 2077146000
-
1
tz.transition 2036, 3, :o8, 2090451600
-
1
tz.transition 2036, 10, :o4, 2108595600
-
1
tz.transition 2037, 3, :o8, 2121901200
-
1
tz.transition 2037, 10, :o4, 2140045200
-
1
tz.transition 2038, 3, :o8, 59172253, 24
-
1
tz.transition 2038, 10, :o4, 59177461, 24
-
1
tz.transition 2039, 3, :o8, 59180989, 24
-
1
tz.transition 2039, 10, :o4, 59186197, 24
-
1
tz.transition 2040, 3, :o8, 59189725, 24
-
1
tz.transition 2040, 10, :o4, 59194933, 24
-
1
tz.transition 2041, 3, :o8, 59198629, 24
-
1
tz.transition 2041, 10, :o4, 59203669, 24
-
1
tz.transition 2042, 3, :o8, 59207365, 24
-
1
tz.transition 2042, 10, :o4, 59212405, 24
-
1
tz.transition 2043, 3, :o8, 59216101, 24
-
1
tz.transition 2043, 10, :o4, 59221141, 24
-
1
tz.transition 2044, 3, :o8, 59224837, 24
-
1
tz.transition 2044, 10, :o4, 59230045, 24
-
1
tz.transition 2045, 3, :o8, 59233573, 24
-
1
tz.transition 2045, 10, :o4, 59238781, 24
-
1
tz.transition 2046, 3, :o8, 59242309, 24
-
1
tz.transition 2046, 10, :o4, 59247517, 24
-
1
tz.transition 2047, 3, :o8, 59251213, 24
-
1
tz.transition 2047, 10, :o4, 59256253, 24
-
1
tz.transition 2048, 3, :o8, 59259949, 24
-
1
tz.transition 2048, 10, :o4, 59264989, 24
-
1
tz.transition 2049, 3, :o8, 59268685, 24
-
1
tz.transition 2049, 10, :o4, 59273893, 24
-
1
tz.transition 2050, 3, :o8, 59277421, 24
-
1
tz.transition 2050, 10, :o4, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Warsaw
-
1
include TimezoneDefinition
-
-
1
timezone 'Europe/Warsaw' do |tz|
-
1
tz.offset :o0, 5040, 0, :LMT
-
1
tz.offset :o1, 5040, 0, :WMT
-
1
tz.offset :o2, 3600, 0, :CET
-
1
tz.offset :o3, 3600, 3600, :CEST
-
1
tz.offset :o4, 7200, 0, :EET
-
1
tz.offset :o5, 7200, 3600, :EEST
-
-
1
tz.transition 1879, 12, :o1, 288925853, 120
-
1
tz.transition 1915, 8, :o2, 290485733, 120
-
1
tz.transition 1916, 4, :o3, 29051813, 12
-
1
tz.transition 1916, 9, :o2, 58107299, 24
-
1
tz.transition 1917, 4, :o3, 58112029, 24
-
1
tz.transition 1917, 9, :o2, 58115725, 24
-
1
tz.transition 1918, 4, :o3, 58120765, 24
-
1
tz.transition 1918, 9, :o4, 58124461, 24
-
1
tz.transition 1919, 4, :o5, 4844127, 2
-
1
tz.transition 1919, 9, :o4, 4844435, 2
-
1
tz.transition 1922, 5, :o2, 29078477, 12
-
1
tz.transition 1940, 6, :o3, 58315285, 24
-
1
tz.transition 1942, 11, :o2, 58335973, 24
-
1
tz.transition 1943, 3, :o3, 58339501, 24
-
1
tz.transition 1943, 10, :o2, 58344037, 24
-
1
tz.transition 1944, 4, :o3, 58348405, 24
-
1
tz.transition 1944, 10, :o2, 4862735, 2
-
1
tz.transition 1945, 4, :o3, 58357787, 24
-
1
tz.transition 1945, 10, :o2, 29181125, 12
-
1
tz.transition 1946, 4, :o3, 58366187, 24
-
1
tz.transition 1946, 10, :o2, 58370413, 24
-
1
tz.transition 1947, 5, :o3, 58375429, 24
-
1
tz.transition 1947, 10, :o2, 58379125, 24
-
1
tz.transition 1948, 4, :o3, 58383829, 24
-
1
tz.transition 1948, 10, :o2, 58387861, 24
-
1
tz.transition 1949, 4, :o3, 58392397, 24
-
1
tz.transition 1949, 10, :o2, 58396597, 24
-
1
tz.transition 1957, 6, :o3, 4871983, 2
-
1
tz.transition 1957, 9, :o2, 4872221, 2
-
1
tz.transition 1958, 3, :o3, 4872585, 2
-
1
tz.transition 1958, 9, :o2, 4872949, 2
-
1
tz.transition 1959, 5, :o3, 4873439, 2
-
1
tz.transition 1959, 10, :o2, 4873691, 2
-
1
tz.transition 1960, 4, :o3, 4874055, 2
-
1
tz.transition 1960, 10, :o2, 4874419, 2
-
1
tz.transition 1961, 5, :o3, 4874895, 2
-
1
tz.transition 1961, 10, :o2, 4875147, 2
-
1
tz.transition 1962, 5, :o3, 4875623, 2
-
1
tz.transition 1962, 9, :o2, 4875875, 2
-
1
tz.transition 1963, 5, :o3, 4876351, 2
-
1
tz.transition 1963, 9, :o2, 4876603, 2
-
1
tz.transition 1964, 5, :o3, 4877093, 2
-
1
tz.transition 1964, 9, :o2, 4877331, 2
-
1
tz.transition 1977, 4, :o3, 228873600
-
1
tz.transition 1977, 9, :o2, 243993600
-
1
tz.transition 1978, 4, :o3, 260323200
-
1
tz.transition 1978, 10, :o2, 276048000
-
1
tz.transition 1979, 4, :o3, 291772800
-
1
tz.transition 1979, 9, :o2, 307497600
-
1
tz.transition 1980, 4, :o3, 323827200
-
1
tz.transition 1980, 9, :o2, 338947200
-
1
tz.transition 1981, 3, :o3, 354672000
-
1
tz.transition 1981, 9, :o2, 370396800
-
1
tz.transition 1982, 3, :o3, 386121600
-
1
tz.transition 1982, 9, :o2, 401846400
-
1
tz.transition 1983, 3, :o3, 417571200
-
1
tz.transition 1983, 9, :o2, 433296000
-
1
tz.transition 1984, 3, :o3, 449020800
-
1
tz.transition 1984, 9, :o2, 465350400
-
1
tz.transition 1985, 3, :o3, 481075200
-
1
tz.transition 1985, 9, :o2, 496800000
-
1
tz.transition 1986, 3, :o3, 512524800
-
1
tz.transition 1986, 9, :o2, 528249600
-
1
tz.transition 1987, 3, :o3, 543974400
-
1
tz.transition 1987, 9, :o2, 559699200
-
1
tz.transition 1988, 3, :o3, 575427600
-
1
tz.transition 1988, 9, :o2, 591152400
-
1
tz.transition 1989, 3, :o3, 606877200
-
1
tz.transition 1989, 9, :o2, 622602000
-
1
tz.transition 1990, 3, :o3, 638326800
-
1
tz.transition 1990, 9, :o2, 654656400
-
1
tz.transition 1991, 3, :o3, 670381200
-
1
tz.transition 1991, 9, :o2, 686106000
-
1
tz.transition 1992, 3, :o3, 701830800
-
1
tz.transition 1992, 9, :o2, 717555600
-
1
tz.transition 1993, 3, :o3, 733280400
-
1
tz.transition 1993, 9, :o2, 749005200
-
1
tz.transition 1994, 3, :o3, 764730000
-
1
tz.transition 1994, 9, :o2, 780454800
-
1
tz.transition 1995, 3, :o3, 796179600
-
1
tz.transition 1995, 9, :o2, 811904400
-
1
tz.transition 1996, 3, :o3, 828234000
-
1
tz.transition 1996, 10, :o2, 846378000
-
1
tz.transition 1997, 3, :o3, 859683600
-
1
tz.transition 1997, 10, :o2, 877827600
-
1
tz.transition 1998, 3, :o3, 891133200
-
1
tz.transition 1998, 10, :o2, 909277200
-
1
tz.transition 1999, 3, :o3, 922582800
-
1
tz.transition 1999, 10, :o2, 941331600
-
1
tz.transition 2000, 3, :o3, 954032400
-
1
tz.transition 2000, 10, :o2, 972781200
-
1
tz.transition 2001, 3, :o3, 985482000
-
1
tz.transition 2001, 10, :o2, 1004230800
-
1
tz.transition 2002, 3, :o3, 1017536400
-
1
tz.transition 2002, 10, :o2, 1035680400
-
1
tz.transition 2003, 3, :o3, 1048986000
-
1
tz.transition 2003, 10, :o2, 1067130000
-
1
tz.transition 2004, 3, :o3, 1080435600
-
1
tz.transition 2004, 10, :o2, 1099184400
-
1
tz.transition 2005, 3, :o3, 1111885200
-
1
tz.transition 2005, 10, :o2, 1130634000
-
1
tz.transition 2006, 3, :o3, 1143334800
-
1
tz.transition 2006, 10, :o2, 1162083600
-
1
tz.transition 2007, 3, :o3, 1174784400
-
1
tz.transition 2007, 10, :o2, 1193533200
-
1
tz.transition 2008, 3, :o3, 1206838800
-
1
tz.transition 2008, 10, :o2, 1224982800
-
1
tz.transition 2009, 3, :o3, 1238288400
-
1
tz.transition 2009, 10, :o2, 1256432400
-
1
tz.transition 2010, 3, :o3, 1269738000
-
1
tz.transition 2010, 10, :o2, 1288486800
-
1
tz.transition 2011, 3, :o3, 1301187600
-
1
tz.transition 2011, 10, :o2, 1319936400
-
1
tz.transition 2012, 3, :o3, 1332637200
-
1
tz.transition 2012, 10, :o2, 1351386000
-
1
tz.transition 2013, 3, :o3, 1364691600
-
1
tz.transition 2013, 10, :o2, 1382835600
-
1
tz.transition 2014, 3, :o3, 1396141200
-
1
tz.transition 2014, 10, :o2, 1414285200
-
1
tz.transition 2015, 3, :o3, 1427590800
-
1
tz.transition 2015, 10, :o2, 1445734800
-
1
tz.transition 2016, 3, :o3, 1459040400
-
1
tz.transition 2016, 10, :o2, 1477789200
-
1
tz.transition 2017, 3, :o3, 1490490000
-
1
tz.transition 2017, 10, :o2, 1509238800
-
1
tz.transition 2018, 3, :o3, 1521939600
-
1
tz.transition 2018, 10, :o2, 1540688400
-
1
tz.transition 2019, 3, :o3, 1553994000
-
1
tz.transition 2019, 10, :o2, 1572138000
-
1
tz.transition 2020, 3, :o3, 1585443600
-
1
tz.transition 2020, 10, :o2, 1603587600
-
1
tz.transition 2021, 3, :o3, 1616893200
-
1
tz.transition 2021, 10, :o2, 1635642000
-
1
tz.transition 2022, 3, :o3, 1648342800
-
1
tz.transition 2022, 10, :o2, 1667091600
-
1
tz.transition 2023, 3, :o3, 1679792400
-
1
tz.transition 2023, 10, :o2, 1698541200
-
1
tz.transition 2024, 3, :o3, 1711846800
-
1
tz.transition 2024, 10, :o2, 1729990800
-
1
tz.transition 2025, 3, :o3, 1743296400
-
1
tz.transition 2025, 10, :o2, 1761440400
-
1
tz.transition 2026, 3, :o3, 1774746000
-
1
tz.transition 2026, 10, :o2, 1792890000
-
1
tz.transition 2027, 3, :o3, 1806195600
-
1
tz.transition 2027, 10, :o2, 1824944400
-
1
tz.transition 2028, 3, :o3, 1837645200
-
1
tz.transition 2028, 10, :o2, 1856394000
-
1
tz.transition 2029, 3, :o3, 1869094800
-
1
tz.transition 2029, 10, :o2, 1887843600
-
1
tz.transition 2030, 3, :o3, 1901149200
-
1
tz.transition 2030, 10, :o2, 1919293200
-
1
tz.transition 2031, 3, :o3, 1932598800
-
1
tz.transition 2031, 10, :o2, 1950742800
-
1
tz.transition 2032, 3, :o3, 1964048400
-
1
tz.transition 2032, 10, :o2, 1982797200
-
1
tz.transition 2033, 3, :o3, 1995498000
-
1
tz.transition 2033, 10, :o2, 2014246800
-
1
tz.transition 2034, 3, :o3, 2026947600
-
1
tz.transition 2034, 10, :o2, 2045696400
-
1
tz.transition 2035, 3, :o3, 2058397200
-
1
tz.transition 2035, 10, :o2, 2077146000
-
1
tz.transition 2036, 3, :o3, 2090451600
-
1
tz.transition 2036, 10, :o2, 2108595600
-
1
tz.transition 2037, 3, :o3, 2121901200
-
1
tz.transition 2037, 10, :o2, 2140045200
-
1
tz.transition 2038, 3, :o3, 59172253, 24
-
1
tz.transition 2038, 10, :o2, 59177461, 24
-
1
tz.transition 2039, 3, :o3, 59180989, 24
-
1
tz.transition 2039, 10, :o2, 59186197, 24
-
1
tz.transition 2040, 3, :o3, 59189725, 24
-
1
tz.transition 2040, 10, :o2, 59194933, 24
-
1
tz.transition 2041, 3, :o3, 59198629, 24
-
1
tz.transition 2041, 10, :o2, 59203669, 24
-
1
tz.transition 2042, 3, :o3, 59207365, 24
-
1
tz.transition 2042, 10, :o2, 59212405, 24
-
1
tz.transition 2043, 3, :o3, 59216101, 24
-
1
tz.transition 2043, 10, :o2, 59221141, 24
-
1
tz.transition 2044, 3, :o3, 59224837, 24
-
1
tz.transition 2044, 10, :o2, 59230045, 24
-
1
tz.transition 2045, 3, :o3, 59233573, 24
-
1
tz.transition 2045, 10, :o2, 59238781, 24
-
1
tz.transition 2046, 3, :o3, 59242309, 24
-
1
tz.transition 2046, 10, :o2, 59247517, 24
-
1
tz.transition 2047, 3, :o3, 59251213, 24
-
1
tz.transition 2047, 10, :o2, 59256253, 24
-
1
tz.transition 2048, 3, :o3, 59259949, 24
-
1
tz.transition 2048, 10, :o2, 59264989, 24
-
1
tz.transition 2049, 3, :o3, 59268685, 24
-
1
tz.transition 2049, 10, :o2, 59273893, 24
-
1
tz.transition 2050, 3, :o3, 59277421, 24
-
1
tz.transition 2050, 10, :o2, 59282629, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Europe
-
1
module Zagreb
-
1
include TimezoneDefinition
-
-
1
linked_timezone 'Europe/Zagreb', 'Europe/Belgrade'
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Pacific
-
1
module Apia
-
1
include TimezoneDefinition
-
-
1
timezone 'Pacific/Apia' do |tz|
-
1
tz.offset :o0, 45184, 0, :LMT
-
1
tz.offset :o1, -41216, 0, :LMT
-
1
tz.offset :o2, -41400, 0, :SAMT
-
1
tz.offset :o3, -39600, 0, :WST
-
1
tz.offset :o4, -39600, 3600, :WSDT
-
1
tz.offset :o5, 46800, 3600, :WSDT
-
1
tz.offset :o6, 46800, 0, :WST
-
-
1
tz.transition 1879, 7, :o1, 3250172219, 1350
-
1
tz.transition 1911, 1, :o2, 3265701269, 1350
-
1
tz.transition 1950, 1, :o3, 116797583, 48
-
1
tz.transition 2010, 9, :o4, 1285498800
-
1
tz.transition 2011, 4, :o3, 1301752800
-
1
tz.transition 2011, 9, :o4, 1316872800
-
1
tz.transition 2011, 12, :o5, 1325239200
-
1
tz.transition 2012, 3, :o6, 1333202400
-
1
tz.transition 2012, 9, :o5, 1348927200
-
1
tz.transition 2013, 4, :o6, 1365256800
-
1
tz.transition 2013, 9, :o5, 1380376800
-
1
tz.transition 2014, 4, :o6, 1396706400
-
1
tz.transition 2014, 9, :o5, 1411826400
-
1
tz.transition 2015, 4, :o6, 1428156000
-
1
tz.transition 2015, 9, :o5, 1443276000
-
1
tz.transition 2016, 4, :o6, 1459605600
-
1
tz.transition 2016, 9, :o5, 1474725600
-
1
tz.transition 2017, 4, :o6, 1491055200
-
1
tz.transition 2017, 9, :o5, 1506175200
-
1
tz.transition 2018, 3, :o6, 1522504800
-
1
tz.transition 2018, 9, :o5, 1538229600
-
1
tz.transition 2019, 4, :o6, 1554559200
-
1
tz.transition 2019, 9, :o5, 1569679200
-
1
tz.transition 2020, 4, :o6, 1586008800
-
1
tz.transition 2020, 9, :o5, 1601128800
-
1
tz.transition 2021, 4, :o6, 1617458400
-
1
tz.transition 2021, 9, :o5, 1632578400
-
1
tz.transition 2022, 4, :o6, 1648908000
-
1
tz.transition 2022, 9, :o5, 1664028000
-
1
tz.transition 2023, 4, :o6, 1680357600
-
1
tz.transition 2023, 9, :o5, 1695477600
-
1
tz.transition 2024, 4, :o6, 1712412000
-
1
tz.transition 2024, 9, :o5, 1727532000
-
1
tz.transition 2025, 4, :o6, 1743861600
-
1
tz.transition 2025, 9, :o5, 1758981600
-
1
tz.transition 2026, 4, :o6, 1775311200
-
1
tz.transition 2026, 9, :o5, 1790431200
-
1
tz.transition 2027, 4, :o6, 1806760800
-
1
tz.transition 2027, 9, :o5, 1821880800
-
1
tz.transition 2028, 4, :o6, 1838210400
-
1
tz.transition 2028, 9, :o5, 1853330400
-
1
tz.transition 2029, 3, :o6, 1869660000
-
1
tz.transition 2029, 9, :o5, 1885384800
-
1
tz.transition 2030, 4, :o6, 1901714400
-
1
tz.transition 2030, 9, :o5, 1916834400
-
1
tz.transition 2031, 4, :o6, 1933164000
-
1
tz.transition 2031, 9, :o5, 1948284000
-
1
tz.transition 2032, 4, :o6, 1964613600
-
1
tz.transition 2032, 9, :o5, 1979733600
-
1
tz.transition 2033, 4, :o6, 1996063200
-
1
tz.transition 2033, 9, :o5, 2011183200
-
1
tz.transition 2034, 4, :o6, 2027512800
-
1
tz.transition 2034, 9, :o5, 2042632800
-
1
tz.transition 2035, 3, :o6, 2058962400
-
1
tz.transition 2035, 9, :o5, 2074687200
-
1
tz.transition 2036, 4, :o6, 2091016800
-
1
tz.transition 2036, 9, :o5, 2106136800
-
1
tz.transition 2037, 4, :o6, 2122466400
-
1
tz.transition 2037, 9, :o5, 2137586400
-
1
tz.transition 2038, 4, :o6, 29586205, 12
-
1
tz.transition 2038, 9, :o5, 29588305, 12
-
1
tz.transition 2039, 4, :o6, 29590573, 12
-
1
tz.transition 2039, 9, :o5, 29592673, 12
-
1
tz.transition 2040, 3, :o6, 29594941, 12
-
1
tz.transition 2040, 9, :o5, 29597125, 12
-
1
tz.transition 2041, 4, :o6, 29599393, 12
-
1
tz.transition 2041, 9, :o5, 29601493, 12
-
1
tz.transition 2042, 4, :o6, 29603761, 12
-
1
tz.transition 2042, 9, :o5, 29605861, 12
-
1
tz.transition 2043, 4, :o6, 29608129, 12
-
1
tz.transition 2043, 9, :o5, 29610229, 12
-
1
tz.transition 2044, 4, :o6, 29612497, 12
-
1
tz.transition 2044, 9, :o5, 29614597, 12
-
1
tz.transition 2045, 4, :o6, 29616865, 12
-
1
tz.transition 2045, 9, :o5, 29618965, 12
-
1
tz.transition 2046, 3, :o6, 29621233, 12
-
1
tz.transition 2046, 9, :o5, 29623417, 12
-
1
tz.transition 2047, 4, :o6, 29625685, 12
-
1
tz.transition 2047, 9, :o5, 29627785, 12
-
1
tz.transition 2048, 4, :o6, 29630053, 12
-
1
tz.transition 2048, 9, :o5, 29632153, 12
-
1
tz.transition 2049, 4, :o6, 29634421, 12
-
1
tz.transition 2049, 9, :o5, 29636521, 12
-
1
tz.transition 2050, 4, :o6, 29638789, 12
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Pacific
-
1
module Auckland
-
1
include TimezoneDefinition
-
-
1
timezone 'Pacific/Auckland' do |tz|
-
1
tz.offset :o0, 41944, 0, :LMT
-
1
tz.offset :o1, 41400, 0, :NZMT
-
1
tz.offset :o2, 41400, 3600, :NZST
-
1
tz.offset :o3, 41400, 1800, :NZST
-
1
tz.offset :o4, 43200, 0, :NZST
-
1
tz.offset :o5, 43200, 3600, :NZDT
-
-
1
tz.transition 1868, 11, :o1, 25959290557, 10800
-
1
tz.transition 1927, 11, :o2, 116409125, 48
-
1
tz.transition 1928, 3, :o1, 38804945, 16
-
1
tz.transition 1928, 10, :o3, 116425589, 48
-
1
tz.transition 1929, 3, :o1, 29108245, 12
-
1
tz.transition 1929, 10, :o3, 116443061, 48
-
1
tz.transition 1930, 3, :o1, 29112613, 12
-
1
tz.transition 1930, 10, :o3, 116460533, 48
-
1
tz.transition 1931, 3, :o1, 29116981, 12
-
1
tz.transition 1931, 10, :o3, 116478005, 48
-
1
tz.transition 1932, 3, :o1, 29121433, 12
-
1
tz.transition 1932, 10, :o3, 116495477, 48
-
1
tz.transition 1933, 3, :o1, 29125801, 12
-
1
tz.transition 1933, 10, :o3, 116512949, 48
-
1
tz.transition 1934, 4, :o1, 29130673, 12
-
1
tz.transition 1934, 9, :o3, 116530085, 48
-
1
tz.transition 1935, 4, :o1, 29135041, 12
-
1
tz.transition 1935, 9, :o3, 116547557, 48
-
1
tz.transition 1936, 4, :o1, 29139409, 12
-
1
tz.transition 1936, 9, :o3, 116565029, 48
-
1
tz.transition 1937, 4, :o1, 29143777, 12
-
1
tz.transition 1937, 9, :o3, 116582501, 48
-
1
tz.transition 1938, 4, :o1, 29148145, 12
-
1
tz.transition 1938, 9, :o3, 116599973, 48
-
1
tz.transition 1939, 4, :o1, 29152597, 12
-
1
tz.transition 1939, 9, :o3, 116617445, 48
-
1
tz.transition 1940, 4, :o1, 29156965, 12
-
1
tz.transition 1940, 9, :o3, 116635253, 48
-
1
tz.transition 1945, 12, :o4, 2431821, 1
-
1
tz.transition 1974, 11, :o5, 152632800
-
1
tz.transition 1975, 2, :o4, 162309600
-
1
tz.transition 1975, 10, :o5, 183477600
-
1
tz.transition 1976, 3, :o4, 194968800
-
1
tz.transition 1976, 10, :o5, 215532000
-
1
tz.transition 1977, 3, :o4, 226418400
-
1
tz.transition 1977, 10, :o5, 246981600
-
1
tz.transition 1978, 3, :o4, 257868000
-
1
tz.transition 1978, 10, :o5, 278431200
-
1
tz.transition 1979, 3, :o4, 289317600
-
1
tz.transition 1979, 10, :o5, 309880800
-
1
tz.transition 1980, 3, :o4, 320767200
-
1
tz.transition 1980, 10, :o5, 341330400
-
1
tz.transition 1981, 2, :o4, 352216800
-
1
tz.transition 1981, 10, :o5, 372780000
-
1
tz.transition 1982, 3, :o4, 384271200
-
1
tz.transition 1982, 10, :o5, 404834400
-
1
tz.transition 1983, 3, :o4, 415720800
-
1
tz.transition 1983, 10, :o5, 436284000
-
1
tz.transition 1984, 3, :o4, 447170400
-
1
tz.transition 1984, 10, :o5, 467733600
-
1
tz.transition 1985, 3, :o4, 478620000
-
1
tz.transition 1985, 10, :o5, 499183200
-
1
tz.transition 1986, 3, :o4, 510069600
-
1
tz.transition 1986, 10, :o5, 530632800
-
1
tz.transition 1987, 2, :o4, 541519200
-
1
tz.transition 1987, 10, :o5, 562082400
-
1
tz.transition 1988, 3, :o4, 573573600
-
1
tz.transition 1988, 10, :o5, 594136800
-
1
tz.transition 1989, 3, :o4, 605023200
-
1
tz.transition 1989, 10, :o5, 623772000
-
1
tz.transition 1990, 3, :o4, 637682400
-
1
tz.transition 1990, 10, :o5, 655221600
-
1
tz.transition 1991, 3, :o4, 669132000
-
1
tz.transition 1991, 10, :o5, 686671200
-
1
tz.transition 1992, 3, :o4, 700581600
-
1
tz.transition 1992, 10, :o5, 718120800
-
1
tz.transition 1993, 3, :o4, 732636000
-
1
tz.transition 1993, 10, :o5, 749570400
-
1
tz.transition 1994, 3, :o4, 764085600
-
1
tz.transition 1994, 10, :o5, 781020000
-
1
tz.transition 1995, 3, :o4, 795535200
-
1
tz.transition 1995, 9, :o5, 812469600
-
1
tz.transition 1996, 3, :o4, 826984800
-
1
tz.transition 1996, 10, :o5, 844524000
-
1
tz.transition 1997, 3, :o4, 858434400
-
1
tz.transition 1997, 10, :o5, 875973600
-
1
tz.transition 1998, 3, :o4, 889884000
-
1
tz.transition 1998, 10, :o5, 907423200
-
1
tz.transition 1999, 3, :o4, 921938400
-
1
tz.transition 1999, 10, :o5, 938872800
-
1
tz.transition 2000, 3, :o4, 953388000
-
1
tz.transition 2000, 9, :o5, 970322400
-
1
tz.transition 2001, 3, :o4, 984837600
-
1
tz.transition 2001, 10, :o5, 1002376800
-
1
tz.transition 2002, 3, :o4, 1016287200
-
1
tz.transition 2002, 10, :o5, 1033826400
-
1
tz.transition 2003, 3, :o4, 1047736800
-
1
tz.transition 2003, 10, :o5, 1065276000
-
1
tz.transition 2004, 3, :o4, 1079791200
-
1
tz.transition 2004, 10, :o5, 1096725600
-
1
tz.transition 2005, 3, :o4, 1111240800
-
1
tz.transition 2005, 10, :o5, 1128175200
-
1
tz.transition 2006, 3, :o4, 1142690400
-
1
tz.transition 2006, 9, :o5, 1159624800
-
1
tz.transition 2007, 3, :o4, 1174140000
-
1
tz.transition 2007, 9, :o5, 1191074400
-
1
tz.transition 2008, 4, :o4, 1207404000
-
1
tz.transition 2008, 9, :o5, 1222524000
-
1
tz.transition 2009, 4, :o4, 1238853600
-
1
tz.transition 2009, 9, :o5, 1253973600
-
1
tz.transition 2010, 4, :o4, 1270303200
-
1
tz.transition 2010, 9, :o5, 1285423200
-
1
tz.transition 2011, 4, :o4, 1301752800
-
1
tz.transition 2011, 9, :o5, 1316872800
-
1
tz.transition 2012, 3, :o4, 1333202400
-
1
tz.transition 2012, 9, :o5, 1348927200
-
1
tz.transition 2013, 4, :o4, 1365256800
-
1
tz.transition 2013, 9, :o5, 1380376800
-
1
tz.transition 2014, 4, :o4, 1396706400
-
1
tz.transition 2014, 9, :o5, 1411826400
-
1
tz.transition 2015, 4, :o4, 1428156000
-
1
tz.transition 2015, 9, :o5, 1443276000
-
1
tz.transition 2016, 4, :o4, 1459605600
-
1
tz.transition 2016, 9, :o5, 1474725600
-
1
tz.transition 2017, 4, :o4, 1491055200
-
1
tz.transition 2017, 9, :o5, 1506175200
-
1
tz.transition 2018, 3, :o4, 1522504800
-
1
tz.transition 2018, 9, :o5, 1538229600
-
1
tz.transition 2019, 4, :o4, 1554559200
-
1
tz.transition 2019, 9, :o5, 1569679200
-
1
tz.transition 2020, 4, :o4, 1586008800
-
1
tz.transition 2020, 9, :o5, 1601128800
-
1
tz.transition 2021, 4, :o4, 1617458400
-
1
tz.transition 2021, 9, :o5, 1632578400
-
1
tz.transition 2022, 4, :o4, 1648908000
-
1
tz.transition 2022, 9, :o5, 1664028000
-
1
tz.transition 2023, 4, :o4, 1680357600
-
1
tz.transition 2023, 9, :o5, 1695477600
-
1
tz.transition 2024, 4, :o4, 1712412000
-
1
tz.transition 2024, 9, :o5, 1727532000
-
1
tz.transition 2025, 4, :o4, 1743861600
-
1
tz.transition 2025, 9, :o5, 1758981600
-
1
tz.transition 2026, 4, :o4, 1775311200
-
1
tz.transition 2026, 9, :o5, 1790431200
-
1
tz.transition 2027, 4, :o4, 1806760800
-
1
tz.transition 2027, 9, :o5, 1821880800
-
1
tz.transition 2028, 4, :o4, 1838210400
-
1
tz.transition 2028, 9, :o5, 1853330400
-
1
tz.transition 2029, 3, :o4, 1869660000
-
1
tz.transition 2029, 9, :o5, 1885384800
-
1
tz.transition 2030, 4, :o4, 1901714400
-
1
tz.transition 2030, 9, :o5, 1916834400
-
1
tz.transition 2031, 4, :o4, 1933164000
-
1
tz.transition 2031, 9, :o5, 1948284000
-
1
tz.transition 2032, 4, :o4, 1964613600
-
1
tz.transition 2032, 9, :o5, 1979733600
-
1
tz.transition 2033, 4, :o4, 1996063200
-
1
tz.transition 2033, 9, :o5, 2011183200
-
1
tz.transition 2034, 4, :o4, 2027512800
-
1
tz.transition 2034, 9, :o5, 2042632800
-
1
tz.transition 2035, 3, :o4, 2058962400
-
1
tz.transition 2035, 9, :o5, 2074687200
-
1
tz.transition 2036, 4, :o4, 2091016800
-
1
tz.transition 2036, 9, :o5, 2106136800
-
1
tz.transition 2037, 4, :o4, 2122466400
-
1
tz.transition 2037, 9, :o5, 2137586400
-
1
tz.transition 2038, 4, :o4, 29586205, 12
-
1
tz.transition 2038, 9, :o5, 29588305, 12
-
1
tz.transition 2039, 4, :o4, 29590573, 12
-
1
tz.transition 2039, 9, :o5, 29592673, 12
-
1
tz.transition 2040, 3, :o4, 29594941, 12
-
1
tz.transition 2040, 9, :o5, 29597125, 12
-
1
tz.transition 2041, 4, :o4, 29599393, 12
-
1
tz.transition 2041, 9, :o5, 29601493, 12
-
1
tz.transition 2042, 4, :o4, 29603761, 12
-
1
tz.transition 2042, 9, :o5, 29605861, 12
-
1
tz.transition 2043, 4, :o4, 29608129, 12
-
1
tz.transition 2043, 9, :o5, 29610229, 12
-
1
tz.transition 2044, 4, :o4, 29612497, 12
-
1
tz.transition 2044, 9, :o5, 29614597, 12
-
1
tz.transition 2045, 4, :o4, 29616865, 12
-
1
tz.transition 2045, 9, :o5, 29618965, 12
-
1
tz.transition 2046, 3, :o4, 29621233, 12
-
1
tz.transition 2046, 9, :o5, 29623417, 12
-
1
tz.transition 2047, 4, :o4, 29625685, 12
-
1
tz.transition 2047, 9, :o5, 29627785, 12
-
1
tz.transition 2048, 4, :o4, 29630053, 12
-
1
tz.transition 2048, 9, :o5, 29632153, 12
-
1
tz.transition 2049, 4, :o4, 29634421, 12
-
1
tz.transition 2049, 9, :o5, 29636521, 12
-
1
tz.transition 2050, 4, :o4, 29638789, 12
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Pacific
-
1
module Fakaofo
-
1
include TimezoneDefinition
-
-
1
timezone 'Pacific/Fakaofo' do |tz|
-
1
tz.offset :o0, -41096, 0, :LMT
-
1
tz.offset :o1, -39600, 0, :TKT
-
1
tz.offset :o2, 46800, 0, :TKT
-
-
1
tz.transition 1901, 1, :o1, 26086168537, 10800
-
1
tz.transition 2011, 12, :o2, 1325242800
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Pacific
-
1
module Fiji
-
1
include TimezoneDefinition
-
-
1
timezone 'Pacific/Fiji' do |tz|
-
1
tz.offset :o0, 42820, 0, :LMT
-
1
tz.offset :o1, 43200, 0, :FJT
-
1
tz.offset :o2, 43200, 3600, :FJST
-
-
1
tz.transition 1915, 10, :o1, 10457838739, 4320
-
1
tz.transition 1998, 10, :o2, 909842400
-
1
tz.transition 1999, 2, :o1, 920124000
-
1
tz.transition 1999, 11, :o2, 941896800
-
1
tz.transition 2000, 2, :o1, 951573600
-
1
tz.transition 2009, 11, :o2, 1259416800
-
1
tz.transition 2010, 3, :o1, 1269698400
-
1
tz.transition 2010, 10, :o2, 1287842400
-
1
tz.transition 2011, 3, :o1, 1299333600
-
1
tz.transition 2011, 10, :o2, 1319292000
-
1
tz.transition 2012, 1, :o1, 1327154400
-
1
tz.transition 2012, 10, :o2, 1350741600
-
1
tz.transition 2013, 1, :o1, 1358604000
-
1
tz.transition 2013, 10, :o2, 1382191200
-
1
tz.transition 2014, 1, :o1, 1390053600
-
1
tz.transition 2014, 10, :o2, 1413640800
-
1
tz.transition 2015, 1, :o1, 1421503200
-
1
tz.transition 2015, 10, :o2, 1445090400
-
1
tz.transition 2016, 1, :o1, 1453557600
-
1
tz.transition 2016, 10, :o2, 1477144800
-
1
tz.transition 2017, 1, :o1, 1485007200
-
1
tz.transition 2017, 10, :o2, 1508594400
-
1
tz.transition 2018, 1, :o1, 1516456800
-
1
tz.transition 2018, 10, :o2, 1540044000
-
1
tz.transition 2019, 1, :o1, 1547906400
-
1
tz.transition 2019, 10, :o2, 1571493600
-
1
tz.transition 2020, 1, :o1, 1579356000
-
1
tz.transition 2020, 10, :o2, 1602943200
-
1
tz.transition 2021, 1, :o1, 1611410400
-
1
tz.transition 2021, 10, :o2, 1634997600
-
1
tz.transition 2022, 1, :o1, 1642860000
-
1
tz.transition 2022, 10, :o2, 1666447200
-
1
tz.transition 2023, 1, :o1, 1674309600
-
1
tz.transition 2023, 10, :o2, 1697896800
-
1
tz.transition 2024, 1, :o1, 1705759200
-
1
tz.transition 2024, 10, :o2, 1729346400
-
1
tz.transition 2025, 1, :o1, 1737208800
-
1
tz.transition 2025, 10, :o2, 1760796000
-
1
tz.transition 2026, 1, :o1, 1768658400
-
1
tz.transition 2026, 10, :o2, 1792245600
-
1
tz.transition 2027, 1, :o1, 1800712800
-
1
tz.transition 2027, 10, :o2, 1824300000
-
1
tz.transition 2028, 1, :o1, 1832162400
-
1
tz.transition 2028, 10, :o2, 1855749600
-
1
tz.transition 2029, 1, :o1, 1863612000
-
1
tz.transition 2029, 10, :o2, 1887199200
-
1
tz.transition 2030, 1, :o1, 1895061600
-
1
tz.transition 2030, 10, :o2, 1918648800
-
1
tz.transition 2031, 1, :o1, 1926511200
-
1
tz.transition 2031, 10, :o2, 1950098400
-
1
tz.transition 2032, 1, :o1, 1957960800
-
1
tz.transition 2032, 10, :o2, 1982152800
-
1
tz.transition 2033, 1, :o1, 1990015200
-
1
tz.transition 2033, 10, :o2, 2013602400
-
1
tz.transition 2034, 1, :o1, 2021464800
-
1
tz.transition 2034, 10, :o2, 2045052000
-
1
tz.transition 2035, 1, :o1, 2052914400
-
1
tz.transition 2035, 10, :o2, 2076501600
-
1
tz.transition 2036, 1, :o1, 2084364000
-
1
tz.transition 2036, 10, :o2, 2107951200
-
1
tz.transition 2037, 1, :o1, 2115813600
-
1
tz.transition 2037, 10, :o2, 2139400800
-
1
tz.transition 2038, 1, :o1, 29585365, 12
-
1
tz.transition 2038, 10, :o2, 29588641, 12
-
1
tz.transition 2039, 1, :o1, 29589733, 12
-
1
tz.transition 2039, 10, :o2, 29593009, 12
-
1
tz.transition 2040, 1, :o1, 29594101, 12
-
1
tz.transition 2040, 10, :o2, 29597377, 12
-
1
tz.transition 2041, 1, :o1, 29598469, 12
-
1
tz.transition 2041, 10, :o2, 29601745, 12
-
1
tz.transition 2042, 1, :o1, 29602837, 12
-
1
tz.transition 2042, 10, :o2, 29606113, 12
-
1
tz.transition 2043, 1, :o1, 29607205, 12
-
1
tz.transition 2043, 10, :o2, 29610481, 12
-
1
tz.transition 2044, 1, :o1, 29611657, 12
-
1
tz.transition 2044, 10, :o2, 29614933, 12
-
1
tz.transition 2045, 1, :o1, 29616025, 12
-
1
tz.transition 2045, 10, :o2, 29619301, 12
-
1
tz.transition 2046, 1, :o1, 29620393, 12
-
1
tz.transition 2046, 10, :o2, 29623669, 12
-
1
tz.transition 2047, 1, :o1, 29624761, 12
-
1
tz.transition 2047, 10, :o2, 29628037, 12
-
1
tz.transition 2048, 1, :o1, 29629129, 12
-
1
tz.transition 2048, 10, :o2, 29632405, 12
-
1
tz.transition 2049, 1, :o1, 29633581, 12
-
1
tz.transition 2049, 10, :o2, 29636857, 12
-
1
tz.transition 2050, 1, :o1, 29637949, 12
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Pacific
-
1
module Guadalcanal
-
1
include TimezoneDefinition
-
-
1
timezone 'Pacific/Guadalcanal' do |tz|
-
1
tz.offset :o0, 38388, 0, :LMT
-
1
tz.offset :o1, 39600, 0, :SBT
-
-
1
tz.transition 1912, 9, :o1, 17421667601, 7200
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Pacific
-
1
module Guam
-
1
include TimezoneDefinition
-
-
1
timezone 'Pacific/Guam' do |tz|
-
1
tz.offset :o0, -51660, 0, :LMT
-
1
tz.offset :o1, 34740, 0, :LMT
-
1
tz.offset :o2, 36000, 0, :GST
-
1
tz.offset :o3, 36000, 0, :ChST
-
-
1
tz.transition 1844, 12, :o1, 1149567407, 480
-
1
tz.transition 1900, 12, :o2, 1159384847, 480
-
1
tz.transition 2000, 12, :o3, 977493600
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Pacific
-
1
module Honolulu
-
1
include TimezoneDefinition
-
-
1
timezone 'Pacific/Honolulu' do |tz|
-
1
tz.offset :o0, -37886, 0, :LMT
-
1
tz.offset :o1, -37800, 0, :HST
-
1
tz.offset :o2, -37800, 3600, :HDT
-
1
tz.offset :o3, -36000, 0, :HST
-
-
1
tz.transition 1896, 1, :o1, 104266329343, 43200
-
1
tz.transition 1933, 4, :o2, 116505265, 48
-
1
tz.transition 1933, 5, :o1, 116506291, 48
-
1
tz.transition 1942, 2, :o2, 116659201, 48
-
1
tz.transition 1945, 9, :o1, 116722991, 48
-
1
tz.transition 1947, 6, :o3, 116752561, 48
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Pacific
-
1
module Majuro
-
1
include TimezoneDefinition
-
-
1
timezone 'Pacific/Majuro' do |tz|
-
1
tz.offset :o0, 41088, 0, :LMT
-
1
tz.offset :o1, 39600, 0, :MHT
-
1
tz.offset :o2, 43200, 0, :MHT
-
-
1
tz.transition 1900, 12, :o1, 1086923261, 450
-
1
tz.transition 1969, 9, :o2, 58571881, 24
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Pacific
-
1
module Midway
-
1
include TimezoneDefinition
-
-
1
timezone 'Pacific/Midway' do |tz|
-
1
tz.offset :o0, -42568, 0, :LMT
-
1
tz.offset :o1, -39600, 0, :NST
-
1
tz.offset :o2, -39600, 3600, :NDT
-
1
tz.offset :o3, -39600, 0, :BST
-
1
tz.offset :o4, -39600, 0, :SST
-
-
1
tz.transition 1901, 1, :o1, 26086168721, 10800
-
1
tz.transition 1956, 6, :o2, 58455071, 24
-
1
tz.transition 1956, 9, :o1, 29228627, 12
-
1
tz.transition 1967, 4, :o3, 58549967, 24
-
1
tz.transition 1983, 11, :o4, 439038000
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Pacific
-
1
module Noumea
-
1
include TimezoneDefinition
-
-
1
timezone 'Pacific/Noumea' do |tz|
-
1
tz.offset :o0, 39948, 0, :LMT
-
1
tz.offset :o1, 39600, 0, :NCT
-
1
tz.offset :o2, 39600, 3600, :NCST
-
-
1
tz.transition 1912, 1, :o1, 17419781071, 7200
-
1
tz.transition 1977, 12, :o2, 250002000
-
1
tz.transition 1978, 2, :o1, 257342400
-
1
tz.transition 1978, 12, :o2, 281451600
-
1
tz.transition 1979, 2, :o1, 288878400
-
1
tz.transition 1996, 11, :o2, 849366000
-
1
tz.transition 1997, 3, :o1, 857228400
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Pacific
-
1
module Pago_Pago
-
1
include TimezoneDefinition
-
-
1
timezone 'Pacific/Pago_Pago' do |tz|
-
1
tz.offset :o0, 45432, 0, :LMT
-
1
tz.offset :o1, -40968, 0, :LMT
-
1
tz.offset :o2, -41400, 0, :SAMT
-
1
tz.offset :o3, -39600, 0, :NST
-
1
tz.offset :o4, -39600, 0, :BST
-
1
tz.offset :o5, -39600, 0, :SST
-
-
1
tz.transition 1879, 7, :o1, 2889041969, 1200
-
1
tz.transition 1911, 1, :o2, 2902845569, 1200
-
1
tz.transition 1950, 1, :o3, 116797583, 48
-
1
tz.transition 1967, 4, :o4, 58549967, 24
-
1
tz.transition 1983, 11, :o5, 439038000
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Pacific
-
1
module Port_Moresby
-
1
include TimezoneDefinition
-
-
1
timezone 'Pacific/Port_Moresby' do |tz|
-
1
tz.offset :o0, 35320, 0, :LMT
-
1
tz.offset :o1, 35312, 0, :PMMT
-
1
tz.offset :o2, 36000, 0, :PGT
-
-
1
tz.transition 1879, 12, :o1, 5200664597, 2160
-
1
tz.transition 1894, 12, :o2, 13031248093, 5400
-
end
-
end
-
end
-
end
-
end
-
1
module TZInfo
-
1
module Definitions
-
1
module Pacific
-
1
module Tongatapu
-
1
include TimezoneDefinition
-
-
1
timezone 'Pacific/Tongatapu' do |tz|
-
1
tz.offset :o0, 44360, 0, :LMT
-
1
tz.offset :o1, 44400, 0, :TOT
-
1
tz.offset :o2, 46800, 0, :TOT
-
1
tz.offset :o3, 46800, 3600, :TOST
-
-
1
tz.transition 1900, 12, :o1, 5217231571, 2160
-
1
tz.transition 1940, 12, :o2, 174959639, 72
-
1
tz.transition 1999, 10, :o3, 939214800
-
1
tz.transition 2000, 3, :o2, 953384400
-
1
tz.transition 2000, 11, :o3, 973342800
-
1
tz.transition 2001, 1, :o2, 980596800
-
1
tz.transition 2001, 11, :o3, 1004792400
-
1
tz.transition 2002, 1, :o2, 1012046400
-
end
-
end
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
module TZInfo
-
-
# A Timezone based on a TimezoneInfo.
-
1
class InfoTimezone < Timezone #:nodoc:
-
-
# Constructs a new InfoTimezone with a TimezoneInfo instance.
-
1
def self.new(info)
-
127
tz = super()
-
127
tz.send(:setup, info)
-
127
tz
-
end
-
-
# The identifier of the timezone, e.g. "Europe/Paris".
-
1
def identifier
-
131
@info.identifier
-
end
-
-
1
protected
-
# The TimezoneInfo for this Timezone.
-
1
def info
-
657
@info
-
end
-
-
1
def setup(info)
-
127
@info = info
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
module TZInfo
-
-
1
class LinkedTimezone < InfoTimezone #:nodoc:
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
#
-
# If no TimezonePeriod could be found, PeriodNotFound is raised.
-
1
def period_for_utc(utc)
-
10
@linked_timezone.period_for_utc(utc)
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how abiguities should be resolved.
-
# Raises PeriodNotFound if no periods are found for the given time.
-
1
def periods_for_local(local)
-
@linked_timezone.periods_for_local(local)
-
end
-
-
1
protected
-
1
def setup(info)
-
5
super(info)
-
5
@linked_timezone = Timezone.get(info.link_to_identifier)
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
module TZInfo
-
# Represents a linked timezone defined in a data module.
-
1
class LinkedTimezoneInfo < TimezoneInfo #:nodoc:
-
-
# The zone that provides the data (that this zone is an alias for).
-
1
attr_reader :link_to_identifier
-
-
# Constructs a new TimezoneInfo with an identifier and the identifier
-
# of the zone linked to.
-
1
def initialize(identifier, link_to_identifier)
-
5
super(identifier)
-
5
@link_to_identifier = link_to_identifier
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #@identifier,#@link_to_identifier>"
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
require 'rational' unless defined?(Rational)
-
-
1
module TZInfo
-
-
# Provides a method for getting Rationals for a timezone offset in seconds.
-
# Pre-reduced rationals are returned for all the half-hour intervals between
-
# -14 and +14 hours to avoid having to call gcd at runtime.
-
1
module OffsetRationals #:nodoc:
-
1
@@rational_cache = {
-
-50400 => RubyCoreSupport.rational_new!(-7,12),
-
-48600 => RubyCoreSupport.rational_new!(-9,16),
-
-46800 => RubyCoreSupport.rational_new!(-13,24),
-
-45000 => RubyCoreSupport.rational_new!(-25,48),
-
-43200 => RubyCoreSupport.rational_new!(-1,2),
-
-41400 => RubyCoreSupport.rational_new!(-23,48),
-
-39600 => RubyCoreSupport.rational_new!(-11,24),
-
-37800 => RubyCoreSupport.rational_new!(-7,16),
-
-36000 => RubyCoreSupport.rational_new!(-5,12),
-
-34200 => RubyCoreSupport.rational_new!(-19,48),
-
-32400 => RubyCoreSupport.rational_new!(-3,8),
-
-30600 => RubyCoreSupport.rational_new!(-17,48),
-
-28800 => RubyCoreSupport.rational_new!(-1,3),
-
-27000 => RubyCoreSupport.rational_new!(-5,16),
-
-25200 => RubyCoreSupport.rational_new!(-7,24),
-
-23400 => RubyCoreSupport.rational_new!(-13,48),
-
-21600 => RubyCoreSupport.rational_new!(-1,4),
-
-19800 => RubyCoreSupport.rational_new!(-11,48),
-
-18000 => RubyCoreSupport.rational_new!(-5,24),
-
-16200 => RubyCoreSupport.rational_new!(-3,16),
-
-14400 => RubyCoreSupport.rational_new!(-1,6),
-
-12600 => RubyCoreSupport.rational_new!(-7,48),
-
-10800 => RubyCoreSupport.rational_new!(-1,8),
-
-9000 => RubyCoreSupport.rational_new!(-5,48),
-
-7200 => RubyCoreSupport.rational_new!(-1,12),
-
-5400 => RubyCoreSupport.rational_new!(-1,16),
-
-3600 => RubyCoreSupport.rational_new!(-1,24),
-
-1800 => RubyCoreSupport.rational_new!(-1,48),
-
0 => RubyCoreSupport.rational_new!(0,1),
-
1800 => RubyCoreSupport.rational_new!(1,48),
-
3600 => RubyCoreSupport.rational_new!(1,24),
-
5400 => RubyCoreSupport.rational_new!(1,16),
-
7200 => RubyCoreSupport.rational_new!(1,12),
-
9000 => RubyCoreSupport.rational_new!(5,48),
-
10800 => RubyCoreSupport.rational_new!(1,8),
-
12600 => RubyCoreSupport.rational_new!(7,48),
-
14400 => RubyCoreSupport.rational_new!(1,6),
-
16200 => RubyCoreSupport.rational_new!(3,16),
-
18000 => RubyCoreSupport.rational_new!(5,24),
-
19800 => RubyCoreSupport.rational_new!(11,48),
-
21600 => RubyCoreSupport.rational_new!(1,4),
-
23400 => RubyCoreSupport.rational_new!(13,48),
-
25200 => RubyCoreSupport.rational_new!(7,24),
-
27000 => RubyCoreSupport.rational_new!(5,16),
-
28800 => RubyCoreSupport.rational_new!(1,3),
-
30600 => RubyCoreSupport.rational_new!(17,48),
-
32400 => RubyCoreSupport.rational_new!(3,8),
-
34200 => RubyCoreSupport.rational_new!(19,48),
-
36000 => RubyCoreSupport.rational_new!(5,12),
-
37800 => RubyCoreSupport.rational_new!(7,16),
-
39600 => RubyCoreSupport.rational_new!(11,24),
-
41400 => RubyCoreSupport.rational_new!(23,48),
-
43200 => RubyCoreSupport.rational_new!(1,2),
-
45000 => RubyCoreSupport.rational_new!(25,48),
-
46800 => RubyCoreSupport.rational_new!(13,24),
-
48600 => RubyCoreSupport.rational_new!(9,16),
-
50400 => RubyCoreSupport.rational_new!(7,12)}
-
-
# Returns a Rational expressing the fraction of a day that offset in
-
# seconds represents (i.e. equivalent to Rational(offset, 86400)).
-
1
def rational_for_offset(offset)
-
22
@@rational_cache[offset] || Rational(offset, 86400)
-
end
-
1
module_function :rational_for_offset
-
end
-
end
-
#--
-
# Copyright (c) 2008-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
require 'date'
-
1
require 'rational' unless defined?(Rational)
-
-
1
module TZInfo
-
-
# Methods to support different versions of Ruby.
-
1
module RubyCoreSupport #:nodoc:
-
-
# Use Rational.new! for performance reasons in Ruby 1.8.
-
# This has been removed from 1.9, but Rational performs better.
-
1
if Rational.respond_to? :new!
-
def self.rational_new!(numerator, denominator = 1)
-
Rational.new!(numerator, denominator)
-
end
-
else
-
1
def self.rational_new!(numerator, denominator = 1)
-
86
Rational(numerator, denominator)
-
end
-
end
-
-
# Ruby 1.8.6 introduced new! and deprecated new0.
-
# Ruby 1.9.0 removed new0.
-
# Ruby trunk revision 31668 removed the new! method.
-
# Still support new0 for better performance on older versions of Ruby (new0 indicates
-
# that the rational has already been reduced to its lowest terms).
-
# Fallback to jd with conversion from ajd if new! and new0 are unavailable.
-
1
if DateTime.respond_to? :new!
-
def self.datetime_new!(ajd = 0, of = 0, sg = Date::ITALY)
-
DateTime.new!(ajd, of, sg)
-
end
-
elsif DateTime.respond_to? :new0
-
def self.datetime_new!(ajd = 0, of = 0, sg = Date::ITALY)
-
DateTime.new0(ajd, of, sg)
-
end
-
else
-
1
HALF_DAYS_IN_DAY = rational_new!(1, 2)
-
-
1
def self.datetime_new!(ajd = 0, of = 0, sg = Date::ITALY)
-
# Convert from an Astronomical Julian Day number to a civil Julian Day number.
-
28
jd = ajd + of + HALF_DAYS_IN_DAY
-
-
# Ruby trunk revision 31862 changed the behaviour of DateTime.jd so that it will no
-
# longer accept a fractional civil Julian Day number if further arguments are specified.
-
# Calculate the hours, minutes and seconds to pass to jd.
-
-
28
jd_i = jd.to_i
-
28
jd_i -= 1 if jd < 0
-
28
hours = (jd - jd_i) * 24
-
28
hours_i = hours.to_i
-
28
minutes = (hours - hours_i) * 60
-
28
minutes_i = minutes.to_i
-
28
seconds = (minutes - minutes_i) * 60
-
-
28
DateTime.jd(jd_i, hours_i, minutes_i, seconds, of, sg)
-
end
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
require 'date'
-
1
require 'time'
-
-
1
module TZInfo
-
# Used by TZInfo internally to represent either a Time, DateTime or integer
-
# timestamp (seconds since 1970-01-01 00:00:00).
-
1
class TimeOrDateTime #:nodoc:
-
1
include Comparable
-
-
# Constructs a new TimeOrDateTime. timeOrDateTime can be a Time, DateTime
-
# or an integer. If using a Time or DateTime, any time zone information is
-
# ignored.
-
1
def initialize(timeOrDateTime)
-
1469
@time = nil
-
1469
@datetime = nil
-
1469
@timestamp = nil
-
-
1469
if timeOrDateTime.is_a?(Time)
-
1038
@time = timeOrDateTime
-
1038
@time = Time.utc(@time.year, @time.mon, @time.mday, @time.hour, @time.min, @time.sec) unless @time.zone == 'UTC'
-
1038
@orig = @time
-
431
elsif timeOrDateTime.is_a?(DateTime)
-
70
@datetime = timeOrDateTime
-
70
@datetime = @datetime.new_offset(0) unless @datetime.offset == 0
-
70
@orig = @datetime
-
else
-
361
@timestamp = timeOrDateTime.to_i
-
361
@orig = @timestamp
-
end
-
end
-
-
# Returns the time as a Time.
-
1
def to_time
-
3937
unless @time
-
309
if @timestamp
-
309
@time = Time.at(@timestamp).utc
-
else
-
@time = Time.utc(year, mon, mday, hour, min, sec)
-
end
-
end
-
-
3937
@time
-
end
-
-
# Returns the time as a DateTime.
-
1
def to_datetime
-
238
unless @datetime
-
91
@datetime = DateTime.new(year, mon, mday, hour, min, sec)
-
end
-
-
238
@datetime
-
end
-
-
# Returns the time as an integer timestamp.
-
1
def to_i
-
131
unless @timestamp
-
@timestamp = to_time.to_i
-
end
-
-
131
@timestamp
-
end
-
-
# Returns the time as the original time passed to new.
-
1
def to_orig
-
1979
@orig
-
end
-
-
# Returns a string representation of the TimeOrDateTime.
-
1
def to_s
-
if @orig.is_a?(Time)
-
"Time: #{@orig.to_s}"
-
elsif @orig.is_a?(DateTime)
-
"DateTime: #{@orig.to_s}"
-
else
-
"Timestamp: #{@orig.to_s}"
-
end
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #{@orig.inspect}>"
-
end
-
-
# Returns the year.
-
1
def year
-
741
if @time
-
731
@time.year
-
10
elsif @datetime
-
10
@datetime.year
-
else
-
to_time.year
-
end
-
end
-
-
# Returns the month of the year (1..12).
-
1
def mon
-
741
if @time
-
731
@time.mon
-
10
elsif @datetime
-
10
@datetime.mon
-
else
-
to_time.mon
-
end
-
end
-
1
alias :month :mon
-
-
# Returns the day of the month (1..n).
-
1
def mday
-
91
if @time
-
91
@time.mday
-
elsif @datetime
-
@datetime.mday
-
else
-
to_time.mday
-
end
-
end
-
1
alias :day :mday
-
-
# Returns the hour of the day (0..23).
-
1
def hour
-
91
if @time
-
91
@time.hour
-
elsif @datetime
-
@datetime.hour
-
else
-
to_time.hour
-
end
-
end
-
-
# Returns the minute of the hour (0..59).
-
1
def min
-
91
if @time
-
91
@time.min
-
elsif @datetime
-
@datetime.min
-
else
-
to_time.min
-
end
-
end
-
-
# Returns the second of the minute (0..60). (60 for a leap second).
-
1
def sec
-
91
if @time
-
91
@time.sec
-
elsif @datetime
-
@datetime.sec
-
else
-
to_time.sec
-
end
-
end
-
-
# Compares this TimeOrDateTime with another Time, DateTime, integer
-
# timestamp or TimeOrDateTime. Returns -1, 0 or +1 depending whether the
-
# receiver is less than, equal to, or greater than timeOrDateTime.
-
#
-
# Milliseconds and smaller units are ignored in the comparison.
-
1
def <=>(timeOrDateTime)
-
1979
if timeOrDateTime.is_a?(TimeOrDateTime)
-
1979
orig = timeOrDateTime.to_orig
-
-
1979
if @orig.is_a?(DateTime) || orig.is_a?(DateTime)
-
# If either is a DateTime, assume it is there for a reason
-
# (i.e. for range).
-
114
to_datetime <=> timeOrDateTime.to_datetime
-
1865
elsif orig.is_a?(Time)
-
1865
to_time <=> timeOrDateTime.to_time
-
else
-
to_i <=> timeOrDateTime.to_i
-
end
-
elsif @orig.is_a?(DateTime) || timeOrDateTime.is_a?(DateTime)
-
# If either is a DateTime, assume it is there for a reason
-
# (i.e. for range).
-
to_datetime <=> TimeOrDateTime.wrap(timeOrDateTime).to_datetime
-
elsif timeOrDateTime.is_a?(Time)
-
to_time <=> timeOrDateTime
-
else
-
to_i <=> timeOrDateTime.to_i
-
end
-
end
-
-
# Adds a number of seconds to the TimeOrDateTime. Returns a new
-
# TimeOrDateTime, preserving what the original constructed type was.
-
# If the original type is a Time and the resulting calculation goes out of
-
# range for Times, then an exception will be raised by the Time class.
-
1
def +(seconds)
-
217
if seconds == 0
-
3
self
-
else
-
214
if @orig.is_a?(DateTime)
-
9
TimeOrDateTime.new(@orig + OffsetRationals.rational_for_offset(seconds))
-
else
-
# + defined for Time and integer timestamps
-
205
TimeOrDateTime.new(@orig + seconds)
-
end
-
end
-
end
-
-
# Subtracts a number of seconds from the TimeOrDateTime. Returns a new
-
# TimeOrDateTime, preserving what the original constructed type was.
-
# If the original type is a Time and the resulting calculation goes out of
-
# range for Times, then an exception will be raised by the Time class.
-
1
def -(seconds)
-
71
self + (-seconds)
-
end
-
-
# Similar to the + operator, but for cases where adding would cause a
-
# timestamp or time to go out of the allowed range, converts to a DateTime
-
# based TimeOrDateTime.
-
1
def add_with_convert(seconds)
-
149
if seconds == 0
-
5
self
-
else
-
144
if @orig.is_a?(DateTime)
-
13
TimeOrDateTime.new(@orig + OffsetRationals.rational_for_offset(seconds))
-
else
-
# A Time or timestamp.
-
131
result = to_i + seconds
-
-
131
if result < 0 || result > 2147483647
-
result = TimeOrDateTime.new(to_datetime + OffsetRationals.rational_for_offset(seconds))
-
else
-
131
result = TimeOrDateTime.new(@orig + seconds)
-
end
-
end
-
end
-
end
-
-
# Returns true if todt represents the same time and was originally
-
# constructed with the same type (DateTime, Time or timestamp) as this
-
# TimeOrDateTime.
-
1
def eql?(todt)
-
todt.respond_to?(:to_orig) && to_orig.eql?(todt.to_orig)
-
end
-
-
# Returns a hash of this TimeOrDateTime.
-
1
def hash
-
@orig.hash
-
end
-
-
# If no block is given, returns a TimeOrDateTime wrapping the given
-
# timeOrDateTime. If a block is specified, a TimeOrDateTime is constructed
-
# and passed to the block. The result of the block must be a TimeOrDateTime.
-
# to_orig will be called on the result and the result of to_orig will be
-
# returned.
-
#
-
# timeOrDateTime can be a Time, DateTime, integer timestamp or TimeOrDateTime.
-
# If a TimeOrDateTime is passed in, no new TimeOrDateTime will be constructed,
-
# the passed in value will be used.
-
1
def self.wrap(timeOrDateTime)
-
881
t = timeOrDateTime.is_a?(TimeOrDateTime) ? timeOrDateTime : TimeOrDateTime.new(timeOrDateTime)
-
-
881
if block_given?
-
231
t = yield t
-
-
231
if timeOrDateTime.is_a?(TimeOrDateTime)
-
14
t
-
217
elsif timeOrDateTime.is_a?(Time)
-
207
t.to_time
-
10
elsif timeOrDateTime.is_a?(DateTime)
-
10
t.to_datetime
-
else
-
t.to_i
-
end
-
else
-
650
t
-
end
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2005-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
require 'date'
-
-
1
module TZInfo
-
# Indicate a specified time in a local timezone has more than one
-
# possible time in UTC. This happens when switching from daylight savings time
-
# to normal time where the clocks are rolled back. Thrown by period_for_local
-
# and local_to_utc when using an ambiguous time and not specifying any
-
# means to resolve the ambiguity.
-
1
class AmbiguousTime < StandardError
-
end
-
-
# Thrown to indicate that no TimezonePeriod matching a given time could be found.
-
1
class PeriodNotFound < StandardError
-
end
-
-
# Thrown by Timezone#get if the identifier given is not valid.
-
1
class InvalidTimezoneIdentifier < StandardError
-
end
-
-
# Thrown if an attempt is made to use a timezone created with Timezone.new(nil).
-
1
class UnknownTimezone < StandardError
-
end
-
-
# Timezone is the base class of all timezones. It provides a factory method
-
# get to access timezones by identifier. Once a specific Timezone has been
-
# retrieved, DateTimes, Times and timestamps can be converted between the UTC
-
# and the local time for the zone. For example:
-
#
-
# tz = TZInfo::Timezone.get('America/New_York')
-
# puts tz.utc_to_local(DateTime.new(2005,8,29,15,35,0)).to_s
-
# puts tz.local_to_utc(Time.utc(2005,8,29,11,35,0)).to_s
-
# puts tz.utc_to_local(1125315300).to_s
-
#
-
# Each time conversion method returns an object of the same type it was
-
# passed.
-
#
-
# The timezone information all comes from the tz database
-
# (see http://www.twinsun.com/tz/tz-link.htm)
-
1
class Timezone
-
1
include Comparable
-
-
# Cache of loaded zones by identifier to avoid using require if a zone
-
# has already been loaded.
-
1
@@loaded_zones = {}
-
-
# Whether the timezones index has been loaded yet.
-
1
@@index_loaded = false
-
-
# Default value of the dst parameter of the local_to_utc and
-
# period_for_local methods.
-
1
@@default_dst = nil
-
-
# Sets the default value of the optional dst parameter of the
-
# local_to_utc and period_for_local methods. Can be set to nil, true or
-
# false.
-
#
-
# The value of default_dst defaults to nil if unset.
-
1
def self.default_dst=(value)
-
@@default_dst = value.nil? ? nil : !!value
-
end
-
-
# Gets the default value of the optional dst parameter of the
-
# local_to_utc and period_for_local methods. Can be set to nil, true or
-
# false.
-
1
def self.default_dst
-
@@default_dst
-
end
-
-
# Returns a timezone by its identifier (e.g. "Europe/London",
-
# "America/Chicago" or "UTC").
-
#
-
# Raises InvalidTimezoneIdentifier if the timezone couldn't be found.
-
1
def self.get(identifier)
-
191
instance = @@loaded_zones[identifier]
-
191
unless instance
-
153
raise InvalidTimezoneIdentifier, 'Invalid identifier' if identifier !~ /^[A-Za-z0-9\+\-_]+(\/[A-Za-z0-9\+\-_]+)*$/
-
130
identifier = identifier.gsub(/-/, '__m__').gsub(/\+/, '__p__')
-
130
begin
-
# Use a temporary variable to avoid an rdoc warning
-
130
file = "tzinfo/definitions/#{identifier}".untaint
-
130
require file
-
-
127
m = Definitions
-
127
identifier.split(/\//).each {|part|
-
256
m = m.const_get(part)
-
}
-
-
127
info = m.get
-
-
# Could make Timezone subclasses register an interest in an info
-
# type. Since there are currently only two however, there isn't
-
# much point.
-
127
if info.kind_of?(DataTimezoneInfo)
-
122
instance = DataTimezone.new(info)
-
elsif info.kind_of?(LinkedTimezoneInfo)
-
5
instance = LinkedTimezone.new(info)
-
else
-
raise InvalidTimezoneIdentifier, "No handler for info type #{info.class}"
-
end
-
-
127
@@loaded_zones[instance.identifier] = instance
-
rescue LoadError, NameError => e
-
3
raise InvalidTimezoneIdentifier, e.message
-
end
-
end
-
-
165
instance
-
end
-
-
# Returns a proxy for the Timezone with the given identifier. The proxy
-
# will cause the real timezone to be loaded when an attempt is made to
-
# find a period or convert a time. get_proxy will not validate the
-
# identifier. If an invalid identifier is specified, no exception will be
-
# raised until the proxy is used.
-
1
def self.get_proxy(identifier)
-
TimezoneProxy.new(identifier)
-
end
-
-
# If identifier is nil calls super(), otherwise calls get. An identfier
-
# should always be passed in when called externally.
-
1
def self.new(identifier = nil)
-
443
if identifier
-
get(identifier)
-
else
-
443
super()
-
end
-
end
-
-
# Returns an array containing all the available Timezones.
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
1
def self.all
-
get_proxies(all_identifiers)
-
end
-
-
# Returns an array containing the identifiers of all the available
-
# Timezones.
-
1
def self.all_identifiers
-
load_index
-
Indexes::Timezones.timezones
-
end
-
-
# Returns an array containing all the available Timezones that are based
-
# on data (are not links to other Timezones).
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
1
def self.all_data_zones
-
get_proxies(all_data_zone_identifiers)
-
end
-
-
# Returns an array containing the identifiers of all the available
-
# Timezones that are based on data (are not links to other Timezones)..
-
1
def self.all_data_zone_identifiers
-
load_index
-
Indexes::Timezones.data_timezones
-
end
-
-
# Returns an array containing all the available Timezones that are links
-
# to other Timezones.
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
1
def self.all_linked_zones
-
get_proxies(all_linked_zone_identifiers)
-
end
-
-
# Returns an array containing the identifiers of all the available
-
# Timezones that are links to other Timezones.
-
1
def self.all_linked_zone_identifiers
-
load_index
-
Indexes::Timezones.linked_timezones
-
end
-
-
# Returns all the Timezones defined for all Countries. This is not the
-
# complete set of Timezones as some are not country specific (e.g.
-
# 'Etc/GMT').
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
1
def self.all_country_zones
-
Country.all_codes.inject([]) {|zones,country|
-
zones += Country.get(country).zones
-
}
-
end
-
-
# Returns all the zone identifiers defined for all Countries. This is not the
-
# complete set of zone identifiers as some are not country specific (e.g.
-
# 'Etc/GMT'). You can obtain a Timezone instance for a given identifier
-
# with the get method.
-
1
def self.all_country_zone_identifiers
-
Country.all_codes.inject([]) {|zones,country|
-
zones += Country.get(country).zone_identifiers
-
}
-
end
-
-
# Returns all US Timezone instances. A shortcut for
-
# TZInfo::Country.get('US').zones.
-
#
-
# Returns TimezoneProxy objects to avoid the overhead of loading Timezone
-
# definitions until a conversion is actually required.
-
1
def self.us_zones
-
Country.get('US').zones
-
end
-
-
# Returns all US zone identifiers. A shortcut for
-
# TZInfo::Country.get('US').zone_identifiers.
-
1
def self.us_zone_identifiers
-
Country.get('US').zone_identifiers
-
end
-
-
# The identifier of the timezone, e.g. "Europe/Paris".
-
1
def identifier
-
raise UnknownTimezone, 'TZInfo::Timezone constructed directly'
-
end
-
-
# An alias for identifier.
-
1
def name
-
# Don't use alias, as identifier gets overridden.
-
17
identifier
-
end
-
-
# Returns a friendlier version of the identifier.
-
1
def to_s
-
friendly_identifier
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #{identifier}>"
-
end
-
-
# Returns a friendlier version of the identifier. Set skip_first_part to
-
# omit the first part of the identifier (typically a region name) where
-
# there is more than one part.
-
#
-
# For example:
-
#
-
# Timezone.get('Europe/Paris').friendly_identifier(false) #=> "Europe - Paris"
-
# Timezone.get('Europe/Paris').friendly_identifier(true) #=> "Paris"
-
# Timezone.get('America/Indiana/Knox').friendly_identifier(false) #=> "America - Knox, Indiana"
-
# Timezone.get('America/Indiana/Knox').friendly_identifier(true) #=> "Knox, Indiana"
-
1
def friendly_identifier(skip_first_part = false)
-
parts = identifier.split('/')
-
if parts.empty?
-
# shouldn't happen
-
identifier
-
elsif parts.length == 1
-
parts[0]
-
else
-
if skip_first_part
-
result = ''
-
else
-
result = parts[0] + ' - '
-
end
-
-
parts[1, parts.length - 1].reverse_each {|part|
-
part.gsub!(/_/, ' ')
-
-
if part.index(/[a-z]/)
-
# Missing a space if a lower case followed by an upper case and the
-
# name isn't McXxxx.
-
part.gsub!(/([^M][a-z])([A-Z])/, '\1 \2')
-
part.gsub!(/([M][a-bd-z])([A-Z])/, '\1 \2')
-
-
# Missing an apostrophe if two consecutive upper case characters.
-
part.gsub!(/([A-Z])([A-Z])/, '\1\'\2')
-
end
-
-
result << part
-
result << ', '
-
}
-
-
result.slice!(result.length - 2, 2)
-
result
-
end
-
end
-
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
1
def period_for_utc(utc)
-
raise UnknownTimezone, 'TZInfo::Timezone constructed directly'
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how ambiguities should be resolved.
-
# Returns an empty array if no periods are found for the given time.
-
1
def periods_for_local(local)
-
raise UnknownTimezone, 'TZInfo::Timezone constructed directly'
-
end
-
-
# Returns the TimezonePeriod for the given local time. local can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in local is ignored (it is treated as a time in the current
-
# timezone).
-
#
-
# Warning: There are local times that have no equivalent UTC times (e.g.
-
# in the transition from standard time to daylight savings time). There are
-
# also local times that have more than one UTC equivalent (e.g. in the
-
# transition from daylight savings time to standard time).
-
#
-
# In the first case (no equivalent UTC time), a PeriodNotFound exception
-
# will be raised.
-
#
-
# In the second case (more than one equivalent UTC time), an AmbiguousTime
-
# exception will be raised unless the optional dst parameter or block
-
# handles the ambiguity.
-
#
-
# If the ambiguity is due to a transition from daylight savings time to
-
# standard time, the dst parameter can be used to select whether the
-
# daylight savings time or local time is used. For example,
-
#
-
# Timezone.get('America/New_York').period_for_local(DateTime.new(2004,10,31,1,30,0))
-
#
-
# would raise an AmbiguousTime exception.
-
#
-
# Specifying dst=true would the daylight savings period from April to
-
# October 2004. Specifying dst=false would return the standard period
-
# from October 2004 to April 2005.
-
#
-
# If the dst parameter does not resolve the ambiguity, and a block is
-
# specified, it is called. The block must take a single parameter - an
-
# array of the periods that need to be resolved. The block can select and
-
# return a single period or return nil or an empty array
-
# to cause an AmbiguousTime exception to be raised.
-
#
-
# The default value of the dst parameter can be specified by setting
-
# Timezone.default_dst. If default_dst is not set, or is set to nil, then
-
# an AmbiguousTime exception will be raised in ambiguous situations unless
-
# a block is given to resolve the ambiguity.
-
1
def period_for_local(local, dst = Timezone.default_dst)
-
196
results = periods_for_local(local)
-
-
196
if results.empty?
-
8
raise PeriodNotFound
-
188
elsif results.size < 2
-
186
results.first
-
else
-
# ambiguous result try to resolve
-
-
2
if !dst.nil?
-
6
matches = results.find_all {|period| period.dst? == dst}
-
2
results = matches if !matches.empty?
-
end
-
-
2
if results.size < 2
-
2
results.first
-
else
-
# still ambiguous, try the block
-
-
if block_given?
-
results = yield results
-
end
-
-
if results.is_a?(TimezonePeriod)
-
results
-
elsif results && results.size == 1
-
results.first
-
else
-
raise AmbiguousTime, "#{local} is an ambiguous local time."
-
end
-
end
-
end
-
end
-
-
# Converts a time in UTC to the local timezone. utc can either be
-
# a DateTime, Time or timestamp (Time.to_i). The returned time has the same
-
# type as utc. Any timezone information in utc is ignored (it is treated as
-
# a UTC time).
-
1
def utc_to_local(utc)
-
12
TimeOrDateTime.wrap(utc) {|wrapped|
-
12
period_for_utc(wrapped).to_local(wrapped)
-
}
-
end
-
-
# Converts a time in the local timezone to UTC. local can either be
-
# a DateTime, Time or timestamp (Time.to_i). The returned time has the same
-
# type as local. Any timezone information in local is ignored (it is treated
-
# as a local time).
-
#
-
# Warning: There are local times that have no equivalent UTC times (e.g.
-
# in the transition from standard time to daylight savings time). There are
-
# also local times that have more than one UTC equivalent (e.g. in the
-
# transition from daylight savings time to standard time).
-
#
-
# In the first case (no equivalent UTC time), a PeriodNotFound exception
-
# will be raised.
-
#
-
# In the second case (more than one equivalent UTC time), an AmbiguousTime
-
# exception will be raised unless the optional dst parameter or block
-
# handles the ambiguity.
-
#
-
# If the ambiguity is due to a transition from daylight savings time to
-
# standard time, the dst parameter can be used to select whether the
-
# daylight savings time or local time is used. For example,
-
#
-
# Timezone.get('America/New_York').local_to_utc(DateTime.new(2004,10,31,1,30,0))
-
#
-
# would raise an AmbiguousTime exception.
-
#
-
# Specifying dst=true would return 2004-10-31 5:30:00. Specifying dst=false
-
# would return 2004-10-31 6:30:00.
-
#
-
# If the dst parameter does not resolve the ambiguity, and a block is
-
# specified, it is called. The block must take a single parameter - an
-
# array of the periods that need to be resolved. The block can return a
-
# single period to use to convert the time or return nil or an empty array
-
# to cause an AmbiguousTime exception to be raised.
-
#
-
# The default value of the dst parameter can be specified by setting
-
# Timezone.default_dst. If default_dst is not set, or is set to nil, then
-
# an AmbiguousTime exception will be raised in ambiguous situations unless
-
# a block is given to resolve the ambiguity.
-
1
def local_to_utc(local, dst = Timezone.default_dst)
-
2
TimeOrDateTime.wrap(local) {|wrapped|
-
2
if block_given?
-
period = period_for_local(wrapped, dst) {|periods| yield periods }
-
else
-
2
period = period_for_local(wrapped, dst)
-
end
-
-
2
period.to_utc(wrapped)
-
}
-
end
-
-
# Returns the current time in the timezone as a Time.
-
1
def now
-
8
utc_to_local(Time.now.utc)
-
end
-
-
# Returns the TimezonePeriod for the current time.
-
1
def current_period
-
311
period_for_utc(Time.now.utc)
-
end
-
-
# Returns the current Time and TimezonePeriod as an array. The first element
-
# is the time, the second element is the period.
-
1
def current_period_and_time
-
utc = Time.now.utc
-
period = period_for_utc(utc)
-
[period.to_local(utc), period]
-
end
-
-
1
alias :current_time_and_period :current_period_and_time
-
-
# Converts a time in UTC to local time and returns it as a string
-
# according to the given format. The formatting is identical to
-
# Time.strftime and DateTime.strftime, except %Z is replaced with the
-
# timezone abbreviation for the specified time (for example, EST or EDT).
-
1
def strftime(format, utc = Time.now.utc)
-
period = period_for_utc(utc)
-
local = period.to_local(utc)
-
local = Time.at(local).utc unless local.kind_of?(Time) || local.kind_of?(DateTime)
-
abbreviation = period.abbreviation.to_s.gsub(/%/, '%%')
-
-
format = format.gsub(/(.?)%Z/) do
-
if $1 == '%'
-
# return %%Z so the real strftime treats it as a literal %Z too
-
'%%Z'
-
else
-
"#$1#{abbreviation}"
-
end
-
end
-
-
local.strftime(format)
-
end
-
-
# Compares two Timezones based on their identifier. Returns -1 if tz is less
-
# than self, 0 if tz is equal to self and +1 if tz is greater than self.
-
1
def <=>(tz)
-
identifier <=> tz.identifier
-
end
-
-
# Returns true if and only if the identifier of tz is equal to the
-
# identifier of this Timezone.
-
1
def eql?(tz)
-
self == tz
-
end
-
-
# Returns a hash of this Timezone.
-
1
def hash
-
identifier.hash
-
end
-
-
# Dumps this Timezone for marshalling.
-
1
def _dump(limit)
-
identifier
-
end
-
-
# Loads a marshalled Timezone.
-
1
def self._load(data)
-
Timezone.get(data)
-
end
-
-
1
private
-
# Loads in the index of timezones if it hasn't already been loaded.
-
1
def self.load_index
-
unless @@index_loaded
-
require 'tzinfo/indexes/timezones'
-
@@index_loaded = true
-
end
-
end
-
-
# Returns an array of proxies corresponding to the given array of
-
# identifiers.
-
1
def self.get_proxies(identifiers)
-
identifiers.collect {|identifier| get_proxy(identifier)}
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
module TZInfo
-
-
# TimezoneDefinition is included into Timezone definition modules.
-
# TimezoneDefinition provides the methods for defining timezones.
-
1
module TimezoneDefinition #:nodoc:
-
# Add class methods to the includee.
-
1
def self.append_features(base)
-
127
super
-
127
base.extend(ClassMethods)
-
end
-
-
# Class methods for inclusion.
-
1
module ClassMethods #:nodoc:
-
# Returns and yields a DataTimezoneInfo object to define a timezone.
-
1
def timezone(identifier)
-
122
yield @timezone = DataTimezoneInfo.new(identifier)
-
end
-
-
# Defines a linked timezone.
-
1
def linked_timezone(identifier, link_to_identifier)
-
5
@timezone = LinkedTimezoneInfo.new(identifier, link_to_identifier)
-
end
-
-
# Returns the last TimezoneInfo to be defined with timezone or
-
# linked_timezone.
-
1
def get
-
127
@timezone
-
end
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
module TZInfo
-
# The timezone index file includes TimezoneIndexDefinition which provides
-
# methods used to define timezones in the index.
-
1
module TimezoneIndexDefinition #:nodoc:
-
1
def self.append_features(base)
-
super
-
base.extend(ClassMethods)
-
base.instance_eval do
-
@timezones = []
-
@data_timezones = []
-
@linked_timezones = []
-
end
-
end
-
-
1
module ClassMethods #:nodoc:
-
# Defines a timezone based on data.
-
1
def timezone(identifier)
-
@timezones << identifier
-
@data_timezones << identifier
-
end
-
-
# Defines a timezone which is a link to another timezone.
-
1
def linked_timezone(identifier)
-
@timezones << identifier
-
@linked_timezones << identifier
-
end
-
-
# Returns a frozen array containing the identifiers of all the timezones.
-
# Identifiers appear in the order they were defined in the index.
-
1
def timezones
-
@timezones.freeze
-
end
-
-
# Returns a frozen array containing the identifiers of all data timezones.
-
# Identifiers appear in the order they were defined in the index.
-
1
def data_timezones
-
@data_timezones.freeze
-
end
-
-
# Returns a frozen array containing the identifiers of all linked
-
# timezones. Identifiers appear in the order they were defined in
-
# the index.
-
1
def linked_timezones
-
@linked_timezones.freeze
-
end
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
module TZInfo
-
# Represents a timezone defined in a data module.
-
1
class TimezoneInfo #:nodoc:
-
-
# The timezone identifier.
-
1
attr_reader :identifier
-
-
# Constructs a new TimezoneInfo with an identifier.
-
1
def initialize(identifier)
-
127
@identifier = identifier
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #@identifier>"
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
module TZInfo
-
# Represents an offset defined in a Timezone data file.
-
1
class TimezoneOffsetInfo #:nodoc:
-
# The base offset of the timezone from UTC in seconds.
-
1
attr_reader :utc_offset
-
-
# The offset from standard time for the zone in seconds (i.e. non-zero if
-
# daylight savings is being observed).
-
1
attr_reader :std_offset
-
-
# The total offset of this observance from UTC in seconds
-
# (utc_offset + std_offset).
-
1
attr_reader :utc_total_offset
-
-
# The abbreviation that identifies this observance, e.g. "GMT"
-
# (Greenwich Mean Time) or "BST" (British Summer Time) for "Europe/London". The returned identifier is a
-
# symbol.
-
1
attr_reader :abbreviation
-
-
# Constructs a new TimezoneOffsetInfo. utc_offset and std_offset are
-
# specified in seconds.
-
1
def initialize(utc_offset, std_offset, abbreviation)
-
616
@utc_offset = utc_offset
-
616
@std_offset = std_offset
-
616
@abbreviation = abbreviation
-
-
616
@utc_total_offset = @utc_offset + @std_offset
-
end
-
-
# True if std_offset is non-zero.
-
1
def dst?
-
28
@std_offset != 0
-
end
-
-
# Converts a UTC DateTime to local time based on the offset of this period.
-
1
def to_local(utc)
-
146
TimeOrDateTime.wrap(utc) {|wrapped|
-
146
wrapped + @utc_total_offset
-
}
-
end
-
-
# Converts a local DateTime to UTC based on the offset of this period.
-
1
def to_utc(local)
-
71
TimeOrDateTime.wrap(local) {|wrapped|
-
71
wrapped - @utc_total_offset
-
}
-
end
-
-
# Returns true if and only if toi has the same utc_offset, std_offset
-
# and abbreviation as this TimezoneOffsetInfo.
-
1
def ==(toi)
-
toi.respond_to?(:utc_offset) && toi.respond_to?(:std_offset) && toi.respond_to?(:abbreviation) &&
-
utc_offset == toi.utc_offset && std_offset == toi.std_offset && abbreviation == toi.abbreviation
-
end
-
-
# Returns true if and only if toi has the same utc_offset, std_offset
-
# and abbreviation as this TimezoneOffsetInfo.
-
1
def eql?(toi)
-
self == toi
-
end
-
-
# Returns a hash of this TimezoneOffsetInfo.
-
1
def hash
-
utc_offset.hash ^ std_offset.hash ^ abbreviation.hash
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #@utc_offset,#@std_offset,#@abbreviation>"
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2005-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
module TZInfo
-
# A period of time in a timezone where the same offset from UTC applies.
-
#
-
# All the methods that take times accept instances of Time, DateTime or
-
# integer timestamps.
-
1
class TimezonePeriod
-
# The TimezoneTransitionInfo that defines the start of this TimezonePeriod
-
# (may be nil if unbounded).
-
1
attr_reader :start_transition
-
-
# The TimezoneTransitionInfo that defines the end of this TimezonePeriod
-
# (may be nil if unbounded).
-
1
attr_reader :end_transition
-
-
# The TimezoneOffsetInfo for this period.
-
1
attr_reader :offset
-
-
# Initializes a new TimezonePeriod.
-
1
def initialize(start_transition, end_transition, offset = nil)
-
651
@start_transition = start_transition
-
651
@end_transition = end_transition
-
-
651
if offset
-
7
raise ArgumentError, 'Offset specified with transitions' if @start_transition || @end_transition
-
7
@offset = offset
-
else
-
644
if @start_transition
-
642
@offset = @start_transition.offset
-
elsif @end_transition
-
2
@offset = @end_transition.previous_offset
-
else
-
raise ArgumentError, 'No offset specified and no transitions to determine it from'
-
end
-
end
-
-
651
@utc_total_offset_rational = nil
-
end
-
-
# Base offset of the timezone from UTC (seconds).
-
1
def utc_offset
-
4931
@offset.utc_offset
-
end
-
-
# Offset from the local time where daylight savings is in effect (seconds).
-
# E.g.: utc_offset could be -5 hours. Normally, std_offset would be 0.
-
# During daylight savings, std_offset would typically become +1 hours.
-
1
def std_offset
-
@offset.std_offset
-
end
-
-
# The identifier of this period, e.g. "GMT" (Greenwich Mean Time) or "BST"
-
# (British Summer Time) for "Europe/London". The returned identifier is a
-
# symbol.
-
1
def abbreviation
-
188
@offset.abbreviation
-
end
-
1
alias :zone_identifier :abbreviation
-
-
# Total offset from UTC (seconds). Equal to utc_offset + std_offset.
-
1
def utc_total_offset
-
223
@offset.utc_total_offset
-
end
-
-
# Total offset from UTC (days). Result is a Rational.
-
1
def utc_total_offset_rational
-
unless @utc_total_offset_rational
-
@utc_total_offset_rational = OffsetRationals.rational_for_offset(utc_total_offset)
-
end
-
@utc_total_offset_rational
-
end
-
-
# The start time of the period in UTC as a DateTime. May be nil if unbounded.
-
1
def utc_start
-
@start_transition ? @start_transition.at.to_datetime : nil
-
end
-
-
# The end time of the period in UTC as a DateTime. May be nil if unbounded.
-
1
def utc_end
-
@end_transition ? @end_transition.at.to_datetime : nil
-
end
-
-
# The start time of the period in local time as a DateTime. May be nil if
-
# unbounded.
-
1
def local_start
-
@start_transition ? @start_transition.local_start.to_datetime : nil
-
end
-
-
# The end time of the period in local time as a DateTime. May be nil if
-
# unbounded.
-
1
def local_end
-
@end_transition ? @end_transition.local_end.to_datetime : nil
-
end
-
-
# true if daylight savings is in effect for this period; otherwise false.
-
1
def dst?
-
28
@offset.dst?
-
end
-
-
# true if this period is valid for the given UTC DateTime; otherwise false.
-
1
def valid_for_utc?(utc)
-
utc_after_start?(utc) && utc_before_end?(utc)
-
end
-
-
# true if the given UTC DateTime is after the start of the period
-
# (inclusive); otherwise false.
-
1
def utc_after_start?(utc)
-
!@start_transition || @start_transition.at <= utc
-
end
-
-
# true if the given UTC DateTime is before the end of the period
-
# (exclusive); otherwise false.
-
1
def utc_before_end?(utc)
-
!@end_transition || @end_transition.at > utc
-
end
-
-
# true if this period is valid for the given local DateTime; otherwise false.
-
1
def valid_for_local?(local)
-
local_after_start?(local) && local_before_end?(local)
-
end
-
-
# true if the given local DateTime is after the start of the period
-
# (inclusive); otherwise false.
-
1
def local_after_start?(local)
-
!@start_transition || @start_transition.local_start <= local
-
end
-
-
# true if the given local DateTime is before the end of the period
-
# (exclusive); otherwise false.
-
1
def local_before_end?(local)
-
!@end_transition || @end_transition.local_end > local
-
end
-
-
# Converts a UTC DateTime to local time based on the offset of this period.
-
1
def to_local(utc)
-
146
@offset.to_local(utc)
-
end
-
-
# Converts a local DateTime to UTC based on the offset of this period.
-
1
def to_utc(local)
-
71
@offset.to_utc(local)
-
end
-
-
# Returns true if this TimezonePeriod is equal to p. This compares the
-
# start_transition, end_transition and offset using ==.
-
1
def ==(p)
-
p.respond_to?(:start_transition) && p.respond_to?(:end_transition) &&
-
p.respond_to?(:offset) && start_transition == p.start_transition &&
-
end_transition == p.end_transition && offset == p.offset
-
end
-
-
# Returns true if this TimezonePeriods is equal to p. This compares the
-
# start_transition, end_transition and offset using eql?
-
1
def eql?(p)
-
p.respond_to?(:start_transition) && p.respond_to?(:end_transition) &&
-
p.respond_to?(:offset) && start_transition.eql?(p.start_transition) &&
-
end_transition.eql?(p.end_transition) && offset.eql?(p.offset)
-
end
-
-
# Returns a hash of this TimezonePeriod.
-
1
def hash
-
result = @start_transition.hash ^ @end_transition.hash
-
result ^= @offset.hash unless @start_transition || @end_transition
-
result
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
result = "#<#{self.class}: #{@start_transition.inspect},#{@end_transition.inspect}"
-
result << ",#{@offset.inspect}>" unless @start_transition || @end_transition
-
result + '>'
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2005-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
module TZInfo
-
-
# A proxy class representing a timezone with a given identifier. TimezoneProxy
-
# inherits from Timezone and can be treated like any Timezone loaded with
-
# Timezone.get.
-
#
-
# The first time an attempt is made to access the data for the timezone, the
-
# real Timezone is loaded. If the proxy's identifier was not valid, then an
-
# exception will be raised at this point.
-
1
class TimezoneProxy < Timezone
-
# Construct a new TimezoneProxy for the given identifier. The identifier
-
# is not checked when constructing the proxy. It will be validated on the
-
# when the real Timezone is loaded.
-
1
def self.new(identifier)
-
# Need to override new to undo the behaviour introduced in Timezone#new.
-
316
tzp = super()
-
316
tzp.send(:setup, identifier)
-
316
tzp
-
end
-
-
# The identifier of the timezone, e.g. "Europe/Paris".
-
1
def identifier
-
14
@real_timezone ? @real_timezone.identifier : @identifier
-
end
-
-
# Returns the TimezonePeriod for the given UTC time. utc can either be
-
# a DateTime, Time or integer timestamp (Time.to_i). Any timezone
-
# information in utc is ignored (it is treated as a UTC time).
-
1
def period_for_utc(utc)
-
469
real_timezone.period_for_utc(utc)
-
end
-
-
# Returns the set of TimezonePeriod instances that are valid for the given
-
# local time as an array. If you just want a single period, use
-
# period_for_local instead and specify how abiguities should be resolved.
-
# Returns an empty array if no periods are found for the given time.
-
1
def periods_for_local(local)
-
196
real_timezone.periods_for_local(local)
-
end
-
-
# Dumps this TimezoneProxy for marshalling.
-
1
def _dump(limit)
-
identifier
-
end
-
-
# Loads a marshalled TimezoneProxy.
-
1
def self._load(data)
-
TimezoneProxy.new(data)
-
end
-
-
1
private
-
1
def setup(identifier)
-
316
@identifier = identifier
-
316
@real_timezone = nil
-
end
-
-
1
def real_timezone
-
665
@real_timezone ||= Timezone.get(@identifier)
-
end
-
end
-
end
-
#--
-
# Copyright (c) 2006-2010 Philip Ross
-
#
-
# Permission is hereby granted, free of charge, to any person obtaining a copy
-
# of this software and associated documentation files (the "Software"), to deal
-
# in the Software without restriction, including without limitation the rights
-
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-
# copies of the Software, and to permit persons to whom the Software is
-
# furnished to do so, subject to the following conditions:
-
#
-
# The above copyright notice and this permission notice shall be included in all
-
# copies or substantial portions of the Software.
-
#
-
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-
# THE SOFTWARE.
-
#++
-
-
1
require 'date'
-
-
1
module TZInfo
-
# Represents an offset defined in a Timezone data file.
-
1
class TimezoneTransitionInfo #:nodoc:
-
# The offset this transition changes to (a TimezoneOffsetInfo instance).
-
1
attr_reader :offset
-
-
# The offset this transition changes from (a TimezoneOffsetInfo instance).
-
1
attr_reader :previous_offset
-
-
# The numerator of the DateTime if the transition time is defined as a
-
# DateTime, otherwise the transition time as a timestamp.
-
1
attr_reader :numerator_or_time
-
1
protected :numerator_or_time
-
-
# Either the denominotor of the DateTime if the transition time is defined
-
# as a DateTime, otherwise nil.
-
1
attr_reader :denominator
-
1
protected :denominator
-
-
# Creates a new TimezoneTransitionInfo with the given offset,
-
# previous_offset (both TimezoneOffsetInfo instances) and UTC time.
-
# if denominator is nil, numerator_or_time is treated as a number of
-
# seconds since the epoch. If denominator is specified numerator_or_time
-
# and denominator are used to create a DateTime as follows:
-
#
-
# DateTime.new!(Rational.send(:new!, numerator_or_time, denominator), 0, Date::ITALY)
-
#
-
# For performance reasons, the numerator and denominator must be specified
-
# in their lowest form.
-
1
def initialize(offset, previous_offset, numerator_or_time, denominator = nil)
-
10948
@offset = offset
-
10948
@previous_offset = previous_offset
-
10948
@numerator_or_time = numerator_or_time
-
10948
@denominator = denominator
-
-
10948
@at = nil
-
10948
@local_end = nil
-
10948
@local_start = nil
-
end
-
-
# A TimeOrDateTime instance representing the UTC time when this transition
-
# occurs.
-
1
def at
-
1171
unless @at
-
258
unless @denominator
-
230
@at = TimeOrDateTime.new(@numerator_or_time)
-
else
-
28
r = RubyCoreSupport.rational_new!(@numerator_or_time, @denominator)
-
28
dt = RubyCoreSupport.datetime_new!(r, 0, Date::ITALY)
-
28
@at = TimeOrDateTime.new(dt)
-
end
-
end
-
-
1171
@at
-
end
-
-
# A TimeOrDateTime instance representing the local time when this transition
-
# causes the previous observance to end (calculated from at using
-
# previous_offset).
-
1
def local_end
-
418
@local_end = at.add_with_convert(@previous_offset.utc_total_offset) unless @local_end
-
418
@local_end
-
end
-
-
# A TimeOrDateTime instance representing the local time when this transition
-
# causes the next observance to start (calculated from at using offset).
-
1
def local_start
-
539
@local_start = at.add_with_convert(@offset.utc_total_offset) unless @local_start
-
539
@local_start
-
end
-
-
# Returns true if this TimezoneTransitionInfo is equal to the given
-
# TimezoneTransitionInfo. Two TimezoneTransitionInfo instances are
-
# considered to be equal by == if offset, previous_offset and at are all
-
# equal.
-
1
def ==(tti)
-
tti.respond_to?(:offset) && tti.respond_to?(:previous_offset) && tti.respond_to?(:at) &&
-
offset == tti.offset && previous_offset == tti.previous_offset && at == tti.at
-
end
-
-
# Returns true if this TimezoneTransitionInfo is equal to the given
-
# TimezoneTransitionInfo. Two TimezoneTransitionInfo instances are
-
# considered to be equal by eql? if offset, previous_offset,
-
# numerator_or_time and denominator are all equal. This is stronger than ==,
-
# which just requires the at times to be equal regardless of how they were
-
# originally specified.
-
1
def eql?(tti)
-
tti.respond_to?(:offset) && tti.respond_to?(:previous_offset) &&
-
tti.respond_to?(:numerator_or_time) && tti.respond_to?(:denominator) &&
-
offset == tti.offset && previous_offset == tti.previous_offset &&
-
numerator_or_time == tti.numerator_or_time && denominator == tti.denominator
-
end
-
-
# Returns a hash of this TimezoneTransitionInfo instance.
-
1
def hash
-
@offset.hash ^ @previous_offset.hash ^ @numerator_or_time.hash ^ @denominator.hash
-
end
-
-
# Returns internal object state as a programmer-readable string.
-
1
def inspect
-
"#<#{self.class}: #{at.inspect},#{@offset.inspect}>"
-
end
-
end
-
end